std::unique_ptr 的自定义删除器规范

Custom deleter specifications for std::unique_ptr

我正在阅读 Josuttis 的 C++ 标准库。我找不到对以下示例的 (2) 和 (3) 评论的推理:

D d;  //instance of the deleter type(1)
unique_ptr<int,D> p1(new int, D()); //D must be  MoveConstructible(2)
unique_ptr<int,D> p2(new int, d);  //D must be CopyConstructible(3)

在这种情况下评论 (2) 和 (3) 的原因是什么?

std::unique_ptr 的自定义删除器有哪些规格?

对于情况 2),您使用的是临时文件,因此编译器可以移动它。 在情况 3) 中,您提供了一个无法移动的对象,因此编译器将需要制作一个副本。

规范在 cppreference(构造函数 #3-4)中进行了准确描述,并且直接来自 C++ 标准部分 [unique.ptr.single.ctor]。由于你的D是非引用类型,签名如下:

unique_ptr(pointer p, const A& d);   // your (3)
unique_ptr(pointer p, A&& d);        // your (2)

其中 AD 的同义词。这些构造函数需要:

Requires:

— If D is not an lvalue-reference type then

  • If d is an lvalue or const rvalue then the first constructor of this pair will be selected. D shall satisfy the requirements of CopyConstructible (Table 21), and the copy constructor of Dshall not throw an exception. This unique_ptr will hold a copy of d.
  • Otherwise, d is a non-const rvalue and the second constructor of this pair will be selected. D shall satisfy the requirements of MoveConstructible (Table 20), and the move constructor of D shall not throw an exception. This unique_ptr will hold a value move constructed from d.

第一个要点描述您的案例 (3),第二个要点描述您的案例 (2)。