使独特和完美的转发

使独特和完美的转发

为什么没有std::make_unique标准C+11库中的函数模板?我发现

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)...刻薄?编译器对此有何看法?


三国纷争
浏览 347回答 3
3回答

慕妹3242003

不错,但是Stephan T.Lavavej(更著名的名字是STL)有一个更好的解决方案make_unique,它对数组版本正确工作。#include&nbsp;<memory>#include&nbsp;<type_traits>#include&nbsp;<utility>template&nbsp;<typename&nbsp;T,&nbsp;typename...&nbsp;Args>std: :unique_ptr<T>&nbsp;make_unique_helper(std::false_type,&nbsp;Args&&...&nbsp;args)&nbsp;{ &nbsp;&nbsp;return&nbsp;std::unique_ptr<T>(new&nbsp;T(std::forward<Args>(args)...));}template&nbsp;<typename&nbsp;T,&nbsp;typename...&nbsp;Args>std: &nbsp;&nbsp;:unique_ptr<T>&nbsp;make_unique_helper(std::true_type,&nbsp;Args&&...&nbsp;args)&nbsp;{ &nbsp;&nbsp;&nbsp;static_assert(std::extent<T>::value&nbsp;==&nbsp;0, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"make_unique<T[N]>()&nbsp;is&nbsp;forbidden,&nbsp;please&nbsp;use&nbsp;make_unique<T[]>()."); &nbsp;&nbsp;&nbsp;typedef&nbsp;typename&nbsp;std::remove_extent<T>::type&nbsp;U; &nbsp;&nbsp;&nbsp;return&nbsp;std::unique_ptr<T>(new&nbsp;U[sizeof...(Args)]{std::forward<Args>(args)...});}template&nbsp;<typename&nbsp;T,&nbsp;typename... &nbsp;&nbsp;&nbsp;&nbsp;Args>std::unique_ptr<T>&nbsp;make_unique(Args&&...&nbsp;args)&nbsp;{ &nbsp;&nbsp;&nbsp;return&nbsp;make_unique_helper<T>(std::is_array<T>(),&nbsp;std::forward<Args>(args)...);}这是可以看到的他的核心C+6视频.STL版本make_UNIQUE的更新版本现在可作为N 3656..这个版本被收养变成草案C+14。

aluckdog

std::make_shared不只是简写std::shared_ptr<Type> ptr(new Type(...));..它做了一些你不可能不用它就行。为了完成它的任务,std::shared_ptr除了保存实际指针的存储空间之外,还必须分配跟踪块。但是,因为std::make_shared分配实际对象时,有可能std::make_shared分配两个对象和同一内存块中的跟踪块。所以当std::shared_ptr<Type> ptr = new Type(...);将是两个内存分配(一个用于new,一个在std::shared_ptr跟踪块),std::make_shared<Type>(...)会分配一记忆块。的许多潜在用户来说,这是很重要的。std::shared_ptr..唯一的一件事std::make_unique这样做会稍微方便一些。仅此而已。
打开App,查看更多内容
随时随地看视频慕课网APP