如何将boost :: shared_ptr(或另一个智能指针)附加到对象父级的引用计数器?

Ale*_*x B 2 c++ boost smart-pointers shared-ptr

我记得之前遇到过这个概念,但现在却无法在谷歌中找到它.

如果我有一个类型为A的对象,它直接嵌入一个B类型的对象:

class A {
    B b;
};
Run Code Online (Sandbox Code Playgroud)

我怎么能有一个智能指针B,例如boost::shared_ptr<B>,但使用引用计数A?假设A它自己的实例是堆分配的,我可以安全地使用,例如,获得它的共享计数enable_shared_from_this.

Ale*_*x B 5

D'哦!

shared_ptr文档中找到它.它被称为别名(参见C++ 0x的shared_ptr改进的第III节).

我只需要使用不同的构造函数(或相应的reset函数重载):

template<class Y> shared_ptr( shared_ptr<Y> const & r, T * p );
Run Code Online (Sandbox Code Playgroud)

其工作原理如下(您需要首先将shared_ptr构造为父级):

#include <boost/shared_ptr.hpp>
#include <iostream>

struct A {
    A() : i_(13) {}
    int i_;
};

struct B {
    A a_;
    ~B() { std::cout << "B deleted" << std::endl; }
};

int
main() {
    boost::shared_ptr<A> a;

    {
        boost::shared_ptr<B> b(new B);
        a = boost::shared_ptr<A>(b, &b->a_);
        std::cout << "ref count = " << a.use_count() << std::endl;
    }
    std::cout << "ref count = " << a.use_count() << std::endl;
    std::cout << a->i_ << std::endl;
}
Run Code Online (Sandbox Code Playgroud)