为什么没有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)...
到底是什么?意思是?编译器对此有何看法?
最佳答案
C++ 标准化委员会主席 Herb Sutter 在他的 blog 上写道:
That C++11 doesn’t include
make_unique
is partly an oversight, and it will almost certainly be added in the future.
他还给出了一个与 OP 给出的实现相同的实现。
编辑: std::make_unique
现在是 C++14 的一部分.
关于c++ - make_unique 和完美的转发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7038357/