boost中的shared_ptr的问题
#include <iostream>
using namespace std;
class D: public boost::enable_shared_from_this<D>
{
public:
D()
{
cout<<"D::D()"<<endl;
}
void func()
{
cout<<"D::func()"<<endl;
boost::shared_ptr<D> p = shared_from_this();
}
};
int main()
{
boost::shared_ptr<D> p(new D);
p->func();
return 0;
}
网上解释:
这里 boost::shared_ptr<D> d(new D) 实际上执行了 3 个动作:首先调用 enable_shared_from_this<D> 的构造函数;其次调用 D 的构造函数;最后调用 shared_ptr<D> 的构造函数。是第 3 个动作设置了 enable_shared_from_this<D> 的 weak_ptr 。
这个地方是很违背 c++ 常理和逻辑的,必须小心。
我想知道第三个动作是怎么设置了 enable_shared_from_this<D> 的 weak_ptr?详细点,网上的资料看了很多,这里还是不懂。还有就是求推荐一本学习boost的书籍,谢谢
using namespace std;
class D: public boost::enable_shared_from_this<D>
{
public:
D()
{
cout<<"D::D()"<<endl;
}
void func()
{
cout<<"D::func()"<<endl;
boost::shared_ptr<D> p = shared_from_this();
}
};
int main()
{
boost::shared_ptr<D> p(new D);
p->func();
return 0;
}
网上解释:
这里 boost::shared_ptr<D> d(new D) 实际上执行了 3 个动作:首先调用 enable_shared_from_this<D> 的构造函数;其次调用 D 的构造函数;最后调用 shared_ptr<D> 的构造函数。是第 3 个动作设置了 enable_shared_from_this<D> 的 weak_ptr 。
这个地方是很违背 c++ 常理和逻辑的,必须小心。
我想知道第三个动作是怎么设置了 enable_shared_from_this<D> 的 weak_ptr?详细点,网上的资料看了很多,这里还是不懂。还有就是求推荐一本学习boost的书籍,谢谢
...全文
相关推荐
stl中的智能指针
本文将详细介绍 STL 中的智能指针,包括 std::auto_ptr、boost::scoped_ptr、boost::shared_ptr、boost::scoped_array、boost::shared_array
浅析Boost智能指针:scoped_ptr shared_ptr weak_ptr
Boost库提供了一组智能指针类型,包括scoped_ptr、shared_ptr和weak_ptr,它们各自有特定的用途和限制。
boost_1_68_0.7z
shared_ptr实现了引用计数,使得多个指针可以共享同一块内存,当所有引用消失时,自动释放内存;unique_ptr是独占所有权的智能指针,确保了资源的唯一性;weak_ptr则用于解决循环引用的问题
boost程序库完全开发指南深入c++准标准库第3版-第6章
**shared_ptr**:这是Boost中最常用的智能指针类型之一,对应于C++11标准库中的std::shared_ptr。
shared_ptr只能对new的内存操作
>#include <boost/shared_ptr.hpp>int _tmain(int argc, _TCHAR* argv[]){ int* px = new int(3); boost::shared_ptr


