gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:01:36 25 4
gpt4 key购买 nike

我阅读了《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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com