【发布时间】:2015-11-23 01:18:55
【问题描述】:
由于std::unique_ptr 提供了一种方便的方法来避免内存泄漏并确保异常安全,因此传递它们而不是原始指针是明智的。因此,一个人可能想要(成员)具有类似签名的函数
std::unique_ptr<some_type> foo(some data);
不幸的是,在实现这样的功能时,不能简单地实现
std::unique_ptr<some_type> foo(some data)
{
return { new some_type(data) }; // error
}
但必须改为
std::unique_ptr<some_type> foo(some data)
{
return std::move( std::unique_ptr<some_type>( new some_type(data) ) ); // awkward
}
因为构造函数unique_ptr::unique_ptr(pointer) 是explicit。这个构造函数是 explicit 背后的原因是什么?
创建构造函数explicit 的一个动机是防止意外的隐式类型转换。但是,由于unique_ptr 不能按值传递,这应该不是问题,不是吗?
【问题讨论】:
-
您可以拥有一个
void foo(unique_ptr<T>);并通过int i = 42; foo(&i);调用它 -
在 C++14 中你可以
return std::make_unique<some_type>(data); -
return std::make_unique<some_type>(data);。不幸的是,make_unique在 c++11 中被“遗忘”了,但 c++14 修复了这个问题。在c++11中也可以write your ownmake_unique。 -
而且您不需要在 C++11 中显式地
std::move临时。 -
你抽什么烟? unique_ptr 可以很容易地按值传递。
标签: c++ c++11 unique-ptr explicit-constructor