c++ - 关于 unique_ptr 中原始指针的类型

标签 c++ c++11 unique-ptr

我阅读了《The C++ Standard Library Second Edition》这本书,找到了以下部分:

namespace std {
template <typename T, typename D>
class unique_ptr<T[], D>
{
public:
typedef ... pointer; // may be D::pointer
typedef T element_type;
typedef D deleter_type;
...
};
}

元素类型 T 可能为空,因此唯一指针拥有一个未指定的对象 类型,就像 void* 一样。另请注意,定义了一个类型指针,不一定定义 作为 T*。如果删除器 D 具有指针 typedef,则将使用此类型。在这种情况下, 模板参数 T 只有类型标记的作用,因为没有成员作为 依赖于 T 的 unique_ptr<> 类;一切都取决于指针。 优点是 unique_ptr 因此可以保存其他智能指针。

看完这节,我还是不能理解“一切都取决于指针”的意思。有没有哪位好心人可以提供一些例子?谢谢。

最佳答案

LWG issue 673pointer 添加到 unique_ptr 规范。它包含动机要点:

  • Efforts have been made to better support containers and smart pointers in shared memory contexts. One of the key hurdles in such support is not assuming that a pointer type is actually a T*. This can easily be accomplished for unique_ptr by having the deleter define the pointer type: D::pointer. Furthermore this type can easily be defaulted to T* should the deleter D choose not to define a pointer type (example implementation here[broken link]). This change has no run time overhead. It has no interface overhead on authors of custom delter types. It simply allows (but not requires) authors of custom deleter types to define a smart pointer for the storage type of unique_ptr if they find such functionality useful. std::default_delete is an example of a deleter which defaults pointer to T* by simply ignoring this issue and not including a pointer typedef.

参见 boost::offset_ptr一个可以引用共享内存的智能指针示例。

关于c++ - 关于 unique_ptr 中原始指针的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28807886/

相关文章:

c++ - 使用 dlopen 动态加载 gtkmm 对象

c++ - 将函数模板传递给具有任意参数列表的函数模板

c++ - 使用 map 值初始化 map

c++ - 如何在 DDD(或 gdb)中使用 unique_ptr 调试 C++11 代码?

c++ - boost (反)序列化派生对象的 vector ,使用删除函数(unique_ptr)

c++ - std::make_unique 和 std::unique_ptr 内部有 new 的区别

c++ - 这两个 offsetof 宏有什么区别?

c++ - 如果键名带有点(.),则在 C++ 中使用 ptree 从 json 中获取值

c++ - 我的代码究竟在哪里不符合键和值类型的规范?

C++ & ta_lib - 无法计算出如何使用 TA_MACD 函数