- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在关注文件 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/
提升智能指针can be used with polymorphism,但是如何将子类转换回指针? using namespace boost; // ... shared_ptr a_ptr(new
有什么方法可以从函数中销毁 std::shared_ptr 吗?在下面的示例中,如果我在 main() 中将 sptr 设置为 nullptr,它会“破坏”对象,因此调用它是 Print( ) 失败。
我想知道这个例子是否会导致段错误,因为对象的 dtor 被调用了,我仍然持有指向对象属性的 shared_ptr。 struct foo{ std::shared_ptr const bar
我是一名学习 C++ 的 SWE,并使用 std::unique_ptr 作为对 head 和 next 的引用构建了一个简单的 LinkedList 类。这是基本结构: template stru
可以boost::smart_ptr比如scoped_ptr和shared_ptr可以用在多态中吗? class SomeClass { public: SomeClass() {
我正在尝试建立哪些数据成员基元/对象(超出 T* 指针)boost(或 std,如果它更容易的话) shared_ptr 有,当 shared_ptr 用于访问底层堆时,它将与 T* 指针位于同一 L
作为一个试图理解智能指针的 C++ 新手。我写了下面的代码来检查。 它确实编译并运行了,但我期望我的类的析构函数被调用并从析构函数打印 cout,但它没有。 我们是否需要重载用户定义类中的任何函数,以
鉴于以下情况: class Curve { public: typedef boost::shared_ptr Pointer; // ... private: // ... }; cla
我目前正在做很多关于异常安全的事情。 (Herb Sutter 的 Exceptional C++、C++ FAQ Lite 等) 特别是,我想编写并理解 C++ FAQ Lite 的引用计数示例,但
因此,我只想将智能指针与boost分开,以便在我的项目中使用,因此我被引导使用bcp实用程序。 今天,我将其编译并执行bcp smart_ptr to_copy_to_my_project/。 结果:
我在一个容器中使用 boost::scoped_array,我想进行写时复制,但我担心 scoped_array 无法工作。哪个 boost::smart_ptr 容器最接近 cow-safe 作用域
我找不到一个完整的例子来说明如何消除 shared_ptr 之间的强循环引用。 问题是如何使用 weak_ptr 来“关闭”通用元素链并使用 weak_ptr 访问“下一个”元素。 谢谢。 编辑: 例
scoped_ptr、shared_ptr等boost::smart_ptr可以用在std::map等std容器中吗? class SomeClass { std::map > a_map;
我正在尝试序列化我无法使用 boost::serialization 修改的自定义类,并且我需要将逻辑/计算代码与序列化部分分开。它有一些我必须序列化的 protected 和私有(private)字
我在boost::smart_ptr中找到了以下自旋锁代码: bool try_lock() { return (__sync_lock_test_and_set(&v_, 1) == 0);
我正在关注文件 boost/smart_ptr/detail/operator_bool.hpp 并遇到以下我不理解的代码片段 typedef T * this_type::*unspecified_
我正在尝试在我的 Windows 7 笔记本电脑上轻松开发一个 websocket++ 服务器(vi 还不太好,不想经常使用 ftp)。我将在最后迁移到 Ubuntu 12.10。 我正在使用 Vis
我是一名优秀的程序员,十分优秀!