侵入型共享指针
引言¶
std::shared_ptr
是一种非侵入型共享智能指针,共享技术与共享对象是解耦的。
而侵入型智能指针,是一种将所有权与对象本身耦合在一起的指针,例如OSG::ref_ptr
。
简介¶
侵入型共享指针(Intrusive Shared Pointers),将对象的计数器与对象本身结合了起来。
简单而言,它将std::shared_ptr
的职责抽成了两部分
// 1. 引用计数耦合在对象的基类当中
template<typename T>
class IntrusiveRefCounted {
public:
void addRef() {
m_refCount.fetch_add(1);
}
void release() {
if (m_refCount.fetch_sub(1) == 1) {
delete static_cast<T*>(this);
}
}
private:
std::atomic_int m_refCount{0}; //引用计数器
};
//2.
template<typename T>
class IntrusiveSharedPtr {
public:
IntrusiveSharedPtr() : m_ptr(nullptr) {}
explicit IntrusiveSharedPtr(T* ptr) : m_ptr(ptr) {
if (m_ptr) {
m_ptr->addRef();
}
}
IntrusiveSharedPtr(const IntrusiveSharedPtr<T>& other) : m_ptr(other.m_ptr) {
if (m_ptr) {
m_ptr->addRef();
}
}
~IntrusiveSharedPtr() {
if (m_ptr) {
m_ptr->release();
}
}
IntrusiveSharedPtr<T>& operator=(const IntrusiveSharedPtr<T>& other) {
if (m_ptr != other.m_ptr) {
if (m_ptr) {
m_ptr->release();
}
m_ptr = other.m_ptr;
if (m_ptr) {
m_ptr->addRef();
}
}
return *this;
}
T* get() const {
return m_ptr;
}
T& operator*() const {
return *m_ptr;
}
T* operator->() const {
return m_ptr;
}
operator bool() const {
return m_ptr != nullptr;
}
private:
T* m_ptr;
};
// 需要
class MyObject : public IntrusiveRefCounted<MyObject> {
public:
void doSomething() {
std::cout << "MyObject do something" << std::endl;
}
};