相关疑难解决方法(0)

make_unique和完美的转发

为什么std::make_unique标准C++ 11库中没有函数模板?我发现

std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3));
Run Code Online (Sandbox Code Playgroud)

有点冗长.以下不是更好吗?

auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3);
Run Code Online (Sandbox Code Playgroud)

这隐藏得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)...));
}
Run Code Online (Sandbox Code Playgroud)

我花了很std::forward长时间来编译这些东西,但我不确定它是否正确.是吗?究竟是什么std::forward<Args>(args)...意思?编译器对此做了什么?

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

215
推荐指数
6
解决办法
7万
查看次数