axmol/thirdparty/openal/common/comptr.h

69 lines
1.6 KiB
C
Raw Normal View History

2021-05-14 10:15:42 +08:00
#ifndef COMMON_COMPTR_H
#define COMMON_COMPTR_H
#include <cstddef>
#include <utility>
2022-04-25 12:02:45 +08:00
#include "opthelpers.h"
2021-05-14 10:15:42 +08:00
template<typename T>
class ComPtr {
T *mPtr{nullptr};
public:
ComPtr() noexcept = default;
ComPtr(const ComPtr &rhs) : mPtr{rhs.mPtr} { if(mPtr) mPtr->AddRef(); }
ComPtr(ComPtr&& rhs) noexcept : mPtr{rhs.mPtr} { rhs.mPtr = nullptr; }
ComPtr(std::nullptr_t) noexcept { }
explicit ComPtr(T *ptr) noexcept : mPtr{ptr} { }
~ComPtr() { if(mPtr) mPtr->Release(); }
ComPtr& operator=(const ComPtr &rhs)
{
if(!rhs.mPtr)
{
if(mPtr)
mPtr->Release();
mPtr = nullptr;
}
else
{
rhs.mPtr->AddRef();
try {
if(mPtr)
mPtr->Release();
mPtr = rhs.mPtr;
}
catch(...) {
rhs.mPtr->Release();
throw;
}
}
return *this;
}
ComPtr& operator=(ComPtr&& rhs)
{
2022-04-25 12:02:45 +08:00
if(likely(&rhs != this))
{
if(mPtr) mPtr->Release();
mPtr = std::exchange(rhs.mPtr, nullptr);
}
2021-05-14 10:15:42 +08:00
return *this;
}
2022-04-25 12:02:45 +08:00
explicit operator bool() const noexcept { return mPtr != nullptr; }
2021-05-14 10:15:42 +08:00
T& operator*() const noexcept { return *mPtr; }
T* operator->() const noexcept { return mPtr; }
T* get() const noexcept { return mPtr; }
T** getPtr() noexcept { return &mPtr; }
2022-04-25 12:02:45 +08:00
T* release() noexcept { return std::exchange(mPtr, nullptr); }
2021-05-14 10:15:42 +08:00
void swap(ComPtr &rhs) noexcept { std::swap(mPtr, rhs.mPtr); }
void swap(ComPtr&& rhs) noexcept { std::swap(mPtr, rhs.mPtr); }
};
#endif