// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary // source code may only be used and distributed under the Widevine License // Agreement. // // Reference implementation utilities of OEMCrypto APIs // #ifndef WVOEC_UTIL_SCOPED_OBJECT_H_ #define WVOEC_UTIL_SCOPED_OBJECT_H_ namespace wvoec { namespace util { // A generic wrapper around pointer. This allows for automatic // memory clean up when the ScopedObject variable goes out of scope. // This is intended to be used with OpenSSL/BoringSSL structs. template class ScopedObject { public: ScopedObject() : ptr_(nullptr) {} ScopedObject(Type* ptr) : ptr_(ptr) {} ~ScopedObject() { if (ptr_) { Destructor(ptr_); ptr_ = nullptr; } } // Copy construction and assignment are not allowed. ScopedObject(const ScopedObject& other) = delete; ScopedObject& operator=(const ScopedObject& other) = delete; // Move construction and assignment are allowed. ScopedObject(ScopedObject&& other) : ptr_(other.ptr_) { other.ptr_ = nullptr; } ScopedObject& operator=(ScopedObject&& other) { if (ptr_) { Destructor(ptr_); } ptr_ = other.ptr_; other.ptr_ = nullptr; return *this; } explicit operator bool() const { return ptr_ != nullptr; } Type& operator*() { return *ptr_; } Type* get() const { return ptr_; } Type* operator->() const { return ptr_; } // Releasing the pointer will remove the responsibility of the // ScopedObject to clean up the pointer. Type* release() { Type* temp = ptr_; ptr_ = nullptr; return temp; } void reset(Type* ptr = nullptr) { if (ptr_) { Destructor(ptr_); } ptr_ = ptr; } private: Type* ptr_ = nullptr; }; } // namespace util } // namespace wvoec #endif // WVOEC_UTIL_SCOPED_OBJECT_H_