c++ - 为什么来自 boost::smart_ptr 的 &this_type::px 返回 1?

标签 c++ boost shared-ptr

我正在关注文件 boost/smart_ptr/detail/operator_bool.hpp 并遇到以下我不理解的代码片段

typedef T * this_type::*unspecified_bool_type;

operator unspecified_bool_type() const // never throws
{
    return px == 0? 0: &this_type::px;
}

我用 XCode 写了一些测试代码,&this_type::px 总是返回 1。为什么?

C++ 大师能否分享您的想法?

最佳答案

这是一个被称为Safe Bool Idiom的小技巧.

问题是,如果您将转换运算符写入 bool:

operator bool() const;

然后它可以在一些棘手的情况下使用,例如:1 + sharedp with bool 被 boost 为 int ... stupid嗯?

因此,诀窍是使用可以转换为 bool 但所有其他操作都会在编译期间引发错误的类型。推荐的方法是在类中使用指向成员的指针,并将其 typedef 编辑为显式名称,以便更容易理解错误消息。


在 C++11 中,这个技巧已经过时,因为 explicit 限定符可以应用于转换运算符:

explicit operator bool() const { return px; }

更愉快,不是吗?

关于c++ - 为什么来自 boost::smart_ptr 的 &this_type::px 返回 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10927905/

相关文章:

c++ - std::vector、std::move 和指针失效

c++ - Direct3D 11 深度缓冲区导致黑屏

c++ - 在 C++ 中映射多个键

c++ - Boost 函数赋值抛出异常

c++ - 单例实例和 scoped_ptr

c++ - 为什么在所有情况下都允许指向 shared_ptr 构造的原始指针?

c++ - strncpy() 获取字符串结尾

c++ - boost::asio 和 send() 的使用

c++ - 使用成员函数作为自定义删除器与 std::shared_ptr 的问题

c++ - std::list of boost::shared_ptr 的迭代器问题