std::make_unique
函数模板?我发现这个问题非常困扰。std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3));
有点啰嗦。以下的表述不是更好吗?
auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3);
这样可以很好地隐藏
new
,并且只提到了类型一次。无论如何,这是我对
make_unique
实现的尝试:template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
我花了相当长的时间才使std :: forward
编译通过,但我不确定它是否正确。它是正确的吗?std::forward<Args>(args)...
究竟意味着什么?编译器对此做出了什么样的处理?
unique_ptr
带有第二个模板参数,你应该以某种方式进行适配,这与shared_ptr
不同。 - Kerrek SBmake_unique
进行参数化使用自定义删除器是没有意义的,因为它显然是通过普通的new
进行分配的,因此必须使用普通的delete
:) - fredoverflowmake_unique
将局限于new
分配…… 如果你想写它,那很好,但我可以理解为什么这样的东西不是标准的一部分。 - Kerrek SBmake_unique
模板,因为std::unique_ptr
的构造函数是显式的,所以从函数返回unique_ptr
很冗长。此外,我更喜欢使用auto p = make_unique<foo>(bar, baz)
而不是std::unique_ptr<foo> p(new foo(bar, baz))
。 - Alexandre C.make_unique
将在C++14中出现,详见http://isocpp.org/blog/2013/04/trip-report-iso-c-spring-2013-meeting。 - stefan