关于c++

77 阅读1分钟

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());
    }
};
原理
  1. class enable_shared_from_this has a member named _Wptr and has a friend class shared_ptr
  2. when construct a shared_ptr<A> , we will set a->_Wptr, so that when we call shared_from_this, we will call a->W_ptr.lock(). So we will make a link with source shared_ptr,we just increment the reference count of source shared_ptr.
  3. So, it obvious that, when we call shared_from_this(), we must have a shared_ptr of this object or it will be still crash. So it's good for that we can only get a std::shared_ptr<A> objects from a factory function.