enable_shared_from_this(c ++ 0x):我做错了什么? [英] enable_shared_from_this (c++0x): what am I doing wrong?
问题描述
我只是在即将到来的新c ++标准的智能指针。但是我无法掌握shared_from_this函数的用法。这里是我有:
I'm just toying around with the smart pointers in the upcoming new c++ standard. However I fail to grasp the usage of the shared_from_this function. Here is what I have:
#include <iostream>
#include <memory>
class CVerboseBornAndDie2 : public std::enable_shared_from_this<CVerboseBornAndDie2>
{
public:
std::string m_Name;
CVerboseBornAndDie2(std::string name) : m_Name(name)
{
std::cout << m_Name << " (" << this << ") is born!" << std::endl;
}
virtual ~CVerboseBornAndDie2()
{
std::cout << m_Name << " (" << this << ") is dying!" << std::endl;
}
};
int main(){
CVerboseBornAndDie2* vbad = new CVerboseBornAndDie2("foo");
std::shared_ptr<CVerboseBornAndDie2> p = vbad->shared_from_this();
}
并且它在行中引发std :: bad_weak_ptr异常
and it throws a std::bad_weak_ptr exception in the line
std::shared_ptr<CVerboseBornAndDie2> p = vbad->shared_from_this();
如果我改为
std::shared_ptr<CVerboseBornAndDie2> p(vbad);
它可以工作,然后可以
std::shared_ptr<CVerboseBornAndDie2> p2 = p.get()->shared_from_this();
因此,在使用shared_from_this之前,对象必须属于一个shared_ptr吗?
so must the object belong to one shared_ptr before I can use shared_from_this? But how can I know this beforehand?
推荐答案
这是使用 shared_from_this $ c的前提条件$ c>必须存在至少一个拥有相关对象的
shared_ptr
。这意味着您只能使用 shared_from_this
来检索拥有引用或指针的对象的 shared_ptr
,你不能使用它来确定这样的对象是否由 shared_ptr
拥有。
It is a precondition of using shared_from_this
that there must exist at least one shared_ptr
which owns the object in question. This means that you can only use shared_from_this
to retrieve a shared_ptr
that owns an object to which you have a reference or pointer, you cannot use it to find out if such an object is owned by a shared_ptr
.
您需要返工你的设计,使你或者你保证任何这样的对象是由一个 shared_ptr
管理,或者你不需要知道或最终(最小希望)你创建一些其他管理这种知识的方式。
You need to rework your design so that either you are guaranteed that any such object is being managed by a shared_ptr
or that you don't ever need to know or finally (and least desirably) you create some other way of managing this knowledge.
这篇关于enable_shared_from_this(c ++ 0x):我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!