关于boost的shared_from_this

bigblacktree3 2014-06-29 10:13:27
网上看的一个例子,说明shared_from_this的:
class Y: public enable_shared_from_this<Y>
{
public:

shared_ptr<Y> f()
{
return shared_from_this();
}
}

int main()
{
shared_ptr<Y> p(new Y);
// 调用f获得shared_ptr

shared_ptr<Y> q = p->f();
assert(p == q);
assert(!(p < q || q < p)); // p and q must share ownership

}

我不太清楚shared_ptr<Y> q = p->f();为什么要这样写,shared_ptr<Y> q = p;不是就可以了么,这个例子能说明什么?
还有,什么时候才需要使用shared_from_this呢?
...全文
102 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ri_aje 2014-07-01
  • 打赏
  • 举报
回复
引用 2 楼 bigblacktree3 的回复:
高手,请再帮忙回答一个问题吧。 在书上看到如下代码 FILE* f=fopen("file.txt","r"); if (f==0) { std::cout << "Unable to open file\n"; throw "Unable to open file"; } boost::shared_ptr<FILE> my_shared_file(f, FileCloser()); 可以这样初始化指针么,如果可以那是不是如下的代码也行呢?如果不行,区别在哪里? int *arrInt = new int[10]; boost::shared_ptr<int> spInt = arrInt;
my_shared_file的可以,spInt 不行;区别在于,一个指针指向一个对象,另一个指向一组对象,所以释放 arrInt 需要 delete [],而 shared_ptr 默认调用 delete,这样析构的时候会导致未定义行为。如果非得用 shared_ptr 管理 new[] 指针的话,可以使用自定义 deleter.
bigblacktree3 2014-06-30
  • 打赏
  • 举报
回复
高手,请再帮忙回答一个问题吧。 在书上看到如下代码 FILE* f=fopen("file.txt","r"); if (f==0) { std::cout << "Unable to open file\n"; throw "Unable to open file"; } boost::shared_ptr<FILE> my_shared_file(f, FileCloser()); 可以这样初始化指针么,如果可以那是不是如下的代码也行呢?如果不行,区别在哪里? int *arrInt = new int[10]; boost::shared_ptr<int> spInt = arrInt;
ri_aje 2014-06-30
  • 打赏
  • 举报
回复
这个例子不恰当,在这里 shared_ptr<Y> q = p; 完全可以胜任。 shared_from_this 的应用情况是: 1. 只有一个 Y 类裸指针,并且 2. 知道该裸指针指向的 Y 类对象是由一个 shared_ptr 管理的, 然后, a. 需要从该裸指针构造另一个shared_ptr 管理同一个 Y 对象,并且 b. 不能和已经管理起该对象的 shared_ptr 们形成冲突。 例子,

shared_ptr<Y> g (Y* pointer)
{
    // here, (1) and (2) are satisfied, and you want (a) and (b), so shared_from_this is a must.
    return pointer->f();
}

int main()
{
    shared_ptr<Y> p(new Y);
    g(p->get());
}

64,652

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧