c++ - make_unique 和完美的转发

标签 c++ c++11 variadic-templates unique-ptr perfect-forwarding

为什么没有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/

相关文章:

java - 替代 Java 中的固定大小数组?

c++ - unordered_map find() 和 operator []

c++ - 按值比较可变参数

c++ - 鼠标悬停在 QGraphicsPixmapItem 上后 Qt 显示工具提示

c++ - cartTexture 成员实际上是否正确初始化?

C++ 函数类型

c++ - 两次移动智能指针与复制

c++ - 函数重载的顺序很重要吗?

c++ - 可变参数模板参数转发使用逗号运算符

c++ - C++模板包,折叠两次