由于C++ 11,shared_ptr或unique_ptr构造函数可以有两个参数,第二个参数是删除项。我感兴趣的是这个删除器是如何定义的。
某些 参考文献 只提到删除的返回类型。
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是一个L值引用类型A&,则签名如下:
unique_ptr(pointer p, A& d);
unique_ptr(pointer p, A&& d); c)如果D是一个lvalue-引用类型const A&,则签名如下:
unique_ptr(pointer p, const A& d);
unique_ptr(pointer p, const A&& d);但是,提到 斯坦利·B·利普曼( Stanley .Lippman)的"C++ Primer“第五版,似乎有更多的限制:在Ch 12动态内存中,Sec 12.1,pg 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是删除者,但是有一个隐含的要求,即删除器的第一个参数(即"*p")和shared_ptr构造函数的第一个参数(即"c")具有相同的类型(即“连接”)。
,这个观察是真的吗?如果需要对删除者进行更严格的定义,则签名将更加复杂?。
阿兰·斯托克斯回复后的更新
删除者
shared_ptr<A> 可以定义为
function<B (A *)> deleter;,其中函数是在"functional“中定义的模板,而B可以是任何内容,因为删除器的返回类型并不重要。
的构造函数
shared_ptr<A>可以写成
shared_ptr<A> p(A *, function<B (A *)> )我想“概念轻”是由于对B的任意选择而引入的。
发布于 2014-11-22 10:21:54
在你引用的推荐信中有很多信息:
“通过调用Deleter(Ptr),该对象被销毁.”
“unique_ptr::pointer类型的参数必须是.可调用的”。
这些约束不是由类型系统强制执行的,因此在技术上不是签名的一部分,而是指定为unique_ptr的需求。
https://stackoverflow.com/questions/27075222
复制相似问题