C++11 的 std::shared_ptr<> 提供了一种 bool 运算符。
operator unspecified-bool-type() const;
(由于 bool
类型的 dangers from implicit casting,它不是一个直接的 operator bool() const
。)
为什么 std::weak_ptr<> 没有类似的运算符?我发现自己经常打字
if( !wp.expired() )
当我想打字时
if( wp )
为什么weak_ptr没有bool转换?
最佳答案
if(!wp.expired())
在多线程代码中几乎总是错误检查,因为直接在 if
语句之后指针可能会过期。因此,如果 weak_ptr
正好具有 bool
转换的语义,那么无论如何它都不会被使用。
如果要检查指针是否存活,使用lock
并检查获取到的shared_ptr
。
如果你想知道指针是否已经失效,使用expired
。
如您所见,提供 bool 转换是没有意义的。对于 shared_ptr
,它完全可以。顺便说一句,转换运算符是 explicit operator bool() const noexcept;
在 C++11 中。
关于c++ - 为什么 std::weak_ptr<> 不提供 bool 转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10283007/