[英]Why doesn't std::weak_ptr<> provide a bool conversion?
C++11's std::shared_ptr<> provides a kind of bool operator. C ++ 11的std :: shared_ptr <>提供了一种bool运算符。
operator unspecified-bool-type() const;
(It's not a straight-up operator bool() const
due to the dangers from implicit casting of type bool
.) (由于
bool
类型的隐式转换的危险,它不是一个直接operator bool() const
。)
Why doesn't std::weak_ptr<> have a similar operator? 为什么std :: weak_ptr <>没有类似的运算符? I find myself constantly typing
我发现自己经常打字
if( !wp.expired() )
when I want to type 当我想打字的时候
if( wp )
Why no bool conversion for weak_ptr? 为什么没有针对weak_ptr的bool转换?
if(!wp.expired())
is almost always a wrong check in multithreaded code, because directly after that if
statement the pointer could expire. if(!wp.expired())
在多线程代码中几乎总是一个错误的检查,因为在if
语句之后直接指针可能会到期。 As such, if weak_ptr
had exactly that as the semantics for the bool
conversion, it would never be used anyways. 因此,如果
weak_ptr
与bool
转换的语义完全相同,那么它永远不会被使用。
If you want to check if the pointer is alive, use lock
and check the obtained shared_ptr
. 如果要检查指针是否处于活动状态,请使用
lock
并检查获取的shared_ptr
。
If you want to know if the pointer is dead, use expired
. 如果您想知道指针是否已死,请使用
expired
。
As you can see, it just doesn't make sense to provide a boolean conversion. 如您所见,提供布尔转换没有意义。 For
shared_ptr
, it totally does. 对于
shared_ptr
,它完全可以。 Btw, the conversion operator is explicit operator bool() const noexcept;
顺便说一下,转换运算符是
explicit operator bool() const noexcept;
in C++11. 在C ++ 11中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.