首先,我已阅读列出的所有相关问题。
他们说,“在使用shared_from_this之前,你必须有一个现有的shared_ptr”。据我所知,我不可能违反这个条件。我将 Foo 的实例创建为shared_ptr,并强制它始终创建为shared_ptr。然后,我将共享指针存储在一个集合中。然而,当调用shared_from_this时,我仍然得到bad_weak_ptr异常。
#pragma once
#include <memory>
#include <vector>
//--------------------------------------------------------------------
class Foo : std::enable_shared_from_this<Foo>
{
public:
typedef std::shared_ptr<Foo> SharedPtr;
// Ensure all instances are created as shared_ptr in order to fulfill requirements for shared_from_this
static Foo::SharedPtr Create()
{
return Foo::SharedPtr(new Foo());
};
Foo(const Foo &) = delete;
Foo(Foo &&) = delete;
Foo & operator = (const Foo &) = delete;
Foo & operator = (Foo &&) = delete;
~Foo() {};
// We have to defer the start until we are fully constructed because we share_from_this()
void Start()
{
DoStuff();
}
private:
Foo() {}
void DoStuff()
{
auto self(shared_from_this());
}
};
//--------------------------------------------------------------------
int main()
{
std::vector<Foo::SharedPtr> foos;
Foo::SharedPtr foo = Foo::Create();
foos.emplace_back(foo);
foo->Start();
return 0;
}
你必须继承enable_shared_from_this
with public
说明符根据
从 std::enable_shared_from_this 公开继承为类型 T 提供了一个成员函数shared_from_this。
from http://en.cppreference.com/w/cpp/memory/enable_shared_from_this http://en.cppreference.com/w/cpp/memory/enable_shared_from_this.
所以写
class Foo : public std::enable_shared_from_this<Foo>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)