问题描述
为什么标准 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 完美转发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!