我阅读了《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 673将 pointer
添加到 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 forunique_ptr
by having the deleter define the pointer type:D::pointer
. Furthermore this type can easily be defaulted toT*
should the deleterD
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 ofunique_ptr
if they find such functionality useful.std::default_delete
is an example of a deleter which defaults pointer toT*
by simply ignoring this issue and not including apointer typedef
.
参见 boost::offset_ptr
一个可以引用共享内存的智能指针示例。
关于c++ - 关于 unique_ptr 中原始指针的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28807886/