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_unique
is 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 完美转发


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09