当使用 std::shared_ptr
往往可以利用 std::enable_shared_from_this<T>
这样您就可以访问 shared_from_this()
功能。
使用该函数的一个要求是 shared_from_this()
是指该对象的所有实例都是用 std::shared_ptr
. 虽然这是一个非常好的要求,但感觉非常困难。执行 给该类的未来用户。
如果我创建了一个对象,然后有人--也许是几年后--使用这个类,而没有把它构造成shared_ptr..:
class MyClass : public std::enable_shared_from_this<MyClass>
{
public:
MyClass()
{
}
void doAThing()
{
// something I need done asynchronously
}
void someFunction()
{
std::weak_ptr<MyClass> w (shared_from_this());
// we need to use a lambda that is executed asynchronously and
// so we pass the std::weak_ptr to it to check this object still exists it is executed
std::function<void()> f = [w]()
{
if (! w.expired())
w.lock()->doAThing();
};
callAsynchronously (f); // this function passes the lambda to some queue and executes it asynchronously
}
};
然后有人... 也许是几年后... 使用这个类而没有把它构造成一个shared_ptr...
MyClass m;
m.someFunction();
那么我们就会得到一个运行时崩溃。
libc++abi.dylib: terminating with uncaught exception of type std::__1::bad_weak_ptr: bad_weak_ptr
我想说的是,我知道解决这个问题的方法是:
std::shared_ptr<MyClass> m = std::make_shared<MyClass>();
m->someFunction();
(当然,我们需要确保这个类中的 shared_ptr
存在了足够长的时间来执行异步回调,但我在这里忽略了这一点)。)
我的问题是--我们如何在继承自 std::enable_shared_from_this<T>
以使该对象的任何构造 不 作为 std::shared_ptr
是在 编译时间 而不是在运行时?
下面的代码带有一个 create
-功能对我来说无一例外地奏效。
#include <memory>
class X : public std::enable_shared_from_this<X> {
private:
X() = default;
public:
static std::shared_ptr<X> makeX() {
return std::shared_ptr<X>(new X());
}
void doSth() {
auto sharedPtr = shared_from_this();
// do sth
}
};
int main() {
auto x = X::makeX();
x->doSth();
}