gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:22:54 24 4
gpt4 key购买 nike

我记得以前遇到过这个概念,但是现在谷歌找不到了。

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

class A {
B b;
};

我怎样才能拥有指向B的智能指针? ,即。 G。 boost::shared_ptr<B> , 但使用 A 的引用计数?假设一个 A 的实例本身是堆分配的我可以安全地使用它的共享计数,比如说 enable_shared_from_this .

最佳答案

哦!

shared_ptr 文档中找到它。这称为别名(参见 section III of shared_ptr improvements for C++0x )。

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

template<class Y> shared_ptr( shared_ptr<Y> const & r, T * p );

它是这样工作的(你需要先构造父级的 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;
}

关于c++ - 如何将 boost::shared_ptr(或另一个智能指针)附加到对象父对象的引用计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2755670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com