c++ - 为什么 std::weak_ptr<> 不提供 bool 转换?

标签 c++ c++11 shared-ptr weak-ptr

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/

相关文章:

c++ - C++11 是否允许 vector<const T>?

c++ - 对于无复制/无移动类型,要扩展的最小类是什么?

c++ - 可变参数模板 : invalid use of void expression

c++ - C++ 中全局 `operator delete` 的两种变体是什么?

c++ - bool的bitwise "and"能保证不短路吗?

C++ weak_ptr创建性能

c++ - shared_ptr 如何存储删除器?

c++ - 为什么我不能将shared_from_this 与回调接口(interface)对象一起使用?

c++ - 定义一个结尾没有空终止字符(\0)的字符串

c++ - 套接字编程主机