많은 library가 있긴 한데 CEF 오픈 소스에서 사용하는 간단한 스마트 포인터 입니다.
class CefRefCount {
public:
CefRefCount() : refct_(0) {}
///
// Atomic reference increment.
///
int AddRef() {
return InterlockedIncrement(&refct_); // OS별로 수정.
}
///
// Atomic reference decrement. Delete the object when no references remain.
///
int Release() {
return InterlockedDecrement(&refct_); // OS별로 수정.
}
///
// Return the current number of references.
///
int GetRefCt() { return refct_; }
private:
long refct_; // NOLINT(runtime/int)
};
#define IMPLEMENT_REFCOUNTING(ClassName) \
public: \
int AddRef() { return refct_.AddRef(); } \
int Release() { \
int retval = refct_.Release(); \
if (retval == 0) \
delete this; \
return retval; \
} \
int GetRefCt() { return refct_.GetRefCt(); } \
private: \
CefRefCount refct_;
template <class T>
class CefRefPtr {
public:
CefRefPtr() : ptr_(NULL) {
}
CefRefPtr(T* p) : ptr_(p) { // NOLINT(runtime/explicit)
if (ptr_)
ptr_->AddRef();
}
CefRefPtr(const CefRefPtr<T>& r) : ptr_(r.ptr_) {
if (ptr_)
ptr_->AddRef();
}
~CefRefPtr() {
if (ptr_)
ptr_->Release();
}
T* get() const { return ptr_; }
operator T*() const { return ptr_; }
T* operator->() const { return ptr_; }
CefRefPtr<T>& operator=(T* p) {
// AddRef first so that self assignment should work
if (p)
p->AddRef();
if (ptr_ )
ptr_ ->Release();
ptr_ = p;
return *this;
}
CefRefPtr<T>& operator=(const CefRefPtr<T>& r) {
return *this = r.ptr_;
}
void swap(T** pp) {
T* p = ptr_;
ptr_ = *pp;
*pp = p;
}
void swap(CefRefPtr<T>& r) {
swap(&r.ptr_); // NOLINT(build/include_what_you_use)
}
private:
T* ptr_;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 사용 예제.
class CSample {
public:
CSample();
virtual ~CSample();
IMPLEMENT_REFCOUNTING(CSample); // 선언
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
...
void CTest::foo1() {
CefRefPtr<CSample> sample = new CSample; // 1. sample count 1
foo2(sample);
// 3. sample count 1
}
// 4. foo1종료시 sample 소멸.
....
void CTest::foo2(CefRefPtr<CSample> sample) {
// 2. sample count 2
}
서지윤 7년전 질문