shared_ptr
make_shared_ptr
std::make_shared_ptr<A>() 相较于std::shared_ptr<A>(new A):
- 其只执行一次内存分配,连同A及ref count等一同分配,其效率更高。但是由于weak count的存在,其内存释放要等weak count等于0后,会更占空间
- 避免了内存资源泄漏,如调用
func(std::shared_ptr<A>(new A),funcb()),由于执行顺序的不确定,funcb()异常退出可能会导致内存泄漏 - 对于protect/private construct class, 无法使用
make_shared_ptr
对于protect/private construct class, 可以使用以下方法规避:
class A {
private:
A() {}
public:
static std::shared_ptr<A> Create();
};
std::shared_ptr<A> A::Create() {
class A1 : public A {};
return std::make_shared<A1>();
}
enable_shared_from_this
针对有些时候需要在member function中,使用this指针转化为shared_ptr参数调用一些特定function。为了使其能不被意外释放,在转化为shared_ptr时关联之前的shared_ptr。c++11提供enable_shared_from_this。使用示例如下
class A;
void exampleFunc(const std::shared_ptr<A>& a) {}
class A : public std::enable_shared_from_this<A> {
private:
A() {}
public:
static std::shared_ptr<A> Create() {
// here we can't use std::make_shared, because A() is private
return std::shared_ptr<A>(new A);
}
void callExample() {
exampleFunc(shared_from_this());
}
};
原理
class enable_shared_from_thishas a member named_Wptrand has a friend classshared_ptr- when construct a
shared_ptr<A>, we will seta->_Wptr, so that when we callshared_from_this, we will calla->W_ptr.lock(). So we will make a link with sourceshared_ptr,we just increment the reference count of sourceshared_ptr. - So, it obvious that, when we call
shared_from_this(), we must have ashared_ptrof this object or it will be still crash. So it's good for that we can only get astd::shared_ptr<A>objects from a factory function.