c++如何传递类实例的boost共享指针到嵌套类对象
C++ how to pass a boost shared pointer of this instance of class to nested class object?
我们有(伪代码):
class A
{
A(shared_ptr parent){}
}
class B
{
A *a;
B()
{
a = new A(boost::shared_ptr(this));
}
}
是否有可能在c++中使用shared_ptr做这样的事情,以及如何在实际的c++代码中做到这一点?
您需要enable_shared_from_this
:
#include <memory>
class B : public std::enable_shared_from_this<B>
{
A * a;
public:
B() : a(new A(std::shared_from_this())) { }
};
(这适用于c++ 0x;Boost的工作原理类似)
仅仅从this
中创建一个共享指针是棘手的,因为您可能会把自己的脚射掉。继承enable_shared_from_this
使这更容易。
警告:您使用裸A
指针的构造似乎违背了使用资源管理类的目的。为什么不把a
也变成一个智能指针呢?也许是unique_ptr
?
相关文章:
- 嵌套类、继承和C++中的共享指针
- 如何从另一个嵌套类中调用某个封闭类的嵌套类的函数指针成员的值?
- 如何将值添加到嵌套结构中,该结构在C++中有两个指针
- 释放指向保留嵌套变量内存地址的结构的指针
- 带有指针的嵌套 foreach 循环?
- 包含指针成员的嵌套结构
- 通过嵌套的lambda中的值捕获指针导致Segfault
- 如何从嵌套类中访问指针
- 设计具有两个指向嵌套对象的指针的迭代器
- 通过指向成员的指针对嵌套访问进行编译时评估期间出现 GCC 错误
- 嵌套的 QVector 指针内存处理
- 为什么缺少此嵌套类的指针
- 嵌套类指针的特殊行为
- 嵌套智能指针运算符>
- 指向嵌套类中的成员函数的 C++ 指针
- 嵌套指针类型在iterator_traits有什么用?
- 访问模板参数T的嵌套类型,即使T是指针
- 正在为嵌套结构指针分配内存
- 在与 OpenMP 并行的嵌套 for 循环中写入共享数组(通过指针)如何产生错误的结果
- 嵌套绑定到成员,需要一个指针,得到了一个引用.做什么