make_unique and perfect forwarding(make_unique 完美转发)
问题描述
为什么标准 C++11 库中没有 std::make_unique 函数模板?我发现
Why is there no std::make_unique function template in the standard C++11 library? I find
std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3));
有点啰嗦.下面的不是更好吗?
a bit verbose. Wouldn't the following be much nicer?
auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3);
这很好地隐藏了 new 并且只提到了一次类型.
This hides the new nicely and only mentions the type once.
无论如何,这是我对 make_unique 实现的尝试:
Anyway, here is my attempt at an implementation of 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)... 到底是什么意思?编译器对此有何看法?
It took me quite a while to get the std::forward stuff to compile, but I'm not sure if it's correct. Is it? What exactly does std::forward<Args>(args)... mean? What does the compiler make of that?
推荐答案
C++ 标准化委员会主席 Herb Sutter 在他的 博客上写道:
Herb Sutter, chair of the C++ standardization committee, writes on his blog:
C++11 不包含 make_unique 部分是一个疏忽,而且几乎肯定会在未来添加.
That C++11 doesn’t include
make_uniqueis partly an oversight, and it will almost certainly be added in the future.
他还给出了一个与 OP 给出的实现相同的实现.
He also gives an implementation that is identical with the one given by the OP.
std::make_unique 现在是 C++14.
这篇关于make_unique 完美转发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:make_unique 完美转发
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
