我正在关注文件 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/