Wal*_*ter 7 c++ shared-ptr c++11 c++17
假设我有一个派生自的类 std::enable_shared_from_this
struct foo
: std::enable_shared_from_this<foo>
{
std::shared_ptr<foo> get_shared()
{
return shared_from_this();
}
bool is_shared() const
{
/* implementation ??? */
}
};
foo A;
auto S= A.get_shared(); // UB (pre c++17) or exception (c++17)
Run Code Online (Sandbox Code Playgroud)
在c ++ 17之前,似乎无法检测对象foo是否实际由a管理shared_ptr.正确?
但即使对于c ++ 17,我也不确定如何最好地实现这样的检测.一个明显的方法是
bool foo::is_shared() const
{
try {
shared_from_this();
} catch(...) {
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
但可以try- catch避免?我可以用weak_from_this()吗?怎么样?
您可以在C++ 17中实现is_shared杠杆作用weak_from_this(),如:
bool is_shared() const
{
return !weak_from_this().expired();
}
Run Code Online (Sandbox Code Playgroud)
这是免费的异常,只返回true对象实际上由a管理shared_ptr.
Pre C++ 17没有办法检查,因为shared_from_this()当对象不属于a时,调用是未定义的行为shared_ptr.直到weak_from_this()在C++ 17中引入我们才能访问私有weak_ptr成员std::enable_shared_from_this(通过副本)我们可以以定义的方式检查状态.