简体   繁体   English

std :: unique_ptr的自定义删除程序规范

[英]Custom deleter specifications for std::unique_ptr

I am reading Josuttis` C++ standard library. 我正在阅读Josuttis的C ++标准库。 I could not find the reasoning for the (2) and (3) comments on following example: 在以下示例中,我找不到(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)

What are the reasons for comment (2) and (3) in this context? 在这种情况下,发表评论(2)和(3)的原因是什么?

What are the specifications for custom deleter for std::unique_ptr ? std::unique_ptr自定义删除程序的规范是什么?

For case 2) you are using a temporary, so the compiler can move it. 对于情况2),您使用的是临时文件,因此编译器可以移动它。 On case 3) you are giving an object that cannot be moved, so the compiler will need to make a copy. 在情况3)中,您给出的对象无法移动,因此编译器将需要进行复制。

The specification is accurately described on cppreference (constructors #3-4), and comes directly from the C++ standard section [unique.ptr.single.ctor]. 该规范在cppreference (构造函数3-4)上有准确的描述,直接来自C ++标准部分[unique.ptr.single.ctor]。 Since your D is a non-reference type, the signatures are as follows: 由于您的D是非引用类型,因此签名如下:

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

where A is a synonym for D . 其中AD的同义词。 These constructors require: 这些构造函数要求:

Requires: 要求:

— If D is not an lvalue-reference type then —如果D不是左值引用类型,则

  • If d is an lvalue or const rvalue then the first constructor of this pair will be selected. 如果d是左值或const右值则这对的第一构造函数将被选择。 D shall satisfy the requirements of CopyConstructible (Table 21), and the copy constructor of D shall not throw an exception. D应满足CopyConstructible的要求(表21),并且D的副本构造函数不得引发异常。 This unique_ptr will hold a copy of d . unique_ptr将保存d的副本。
  • Otherwise, d is a non- const rvalue and the second constructor of this pair will be selected. 否则, d是非const右值和该对中的第二构造函数将被选择。 D shall satisfy the requirements of MoveConstructible (Table 20), and the move constructor of D shall not throw an exception. D应满足MoveConstructible的要求(表20),并且D的move构造函数不得引发异常。 This unique_ptr will hold a value move constructed from d . unique_ptr将保存从d构造的值移动。

The first bullet point describes your case (3), the second describes your case (2). 第一个要点描述您的情况(3),第二个要点描述您的情况(2)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM