使用时std::shared_ptr
,它通常很有用,std::enable_shared_from_this<T>
以便您可以访问该shared_from_this()
功能。
using 的一项要求shared_from_this()
是对象的所有实例都使用std::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>
该对象的任何构造而不是a ?std::shared_ptr