【发布时间】:2014-11-24 00:06:09
【问题描述】:
从 C++ 11 开始,shared_ptr 或 unique_ptr 构造函数可以有两个参数,第二个是删除器。 我对这个删除器是如何定义的很感兴趣。
有些reference只提到删除器的返回类型:
unique_ptr( pointer p, /* see below */ d1 ); //(3) (since C++11)
unique_ptr( pointer p, /* see below */ d2 ); //(4) (since C++11)
3-4) 构造一个拥有 p 的 std::unique_ptr 对象,用 p 初始化存储的指针并初始化一个删除器 D,如下所示(取决于 D 是否为引用类型)
a) 如果 D 是非引用类型 A,则签名为:
unique_ptr(pointer p, const A& d); //(requires that Deleter is nothrow-CopyConstructible)
unique_ptr(pointer p, A&& d); // (requires that Deleter is nothrow-MoveConstructible)
b) 如果 D 是左值引用类型 A&,则签名为:
unique_ptr(pointer p, A& d);
unique_ptr(pointer p, A&& d);
c) 如果 D 是左值引用类型 const A&,则签名为:
unique_ptr(pointer p, const A& d);
unique_ptr(pointer p, const A&& d);
但是,参考Stanley B. Lippman's "C++ Primer", 5th edition,似乎有更多限制:在第 12 章动态内存,第 12.1 节,第 469 页:
void end_connection(connection *p) { disconnect(*p); }
void f(destination &d /* other parameters */)
{
connection c = connect(&d);
shared_ptr<connection> p(&c, end_connection);
// use the connection
// when f exits, even if by an exception, the connection will be properly closed
}
这里end_connection是deleter,但是有一个隐含的要求,deleter的第一个参数(即“*p”)和shared_ptr构造函数的第一个参数(即“c”)的类型相同(即“连接”)。
这个观察是真的吗?如果删除器需要更严格的定义,签名会更复杂?
艾伦斯托克斯回复后更新
删除器
shared_ptr<A>
可以定义为
function<B (A *)> deleter;
,其中 function 是定义在“functional”标头中的模板,B 可以是任何东西,因为删除器的返回类型无关紧要。
所以
的构造函数shared_ptr<A>
可以写成
shared_ptr<A> p(A *, function<B (A *)> )
我猜“concept lite”是由于B的任意选择而引入的。
【问题讨论】: