如何将 make_unique 与 c++11 一起使用?

Mat*_*ues -1 c++ unique-ptr

我收到以下错误:

“make_unique”不是“std”的成员

当它编写以下代码时:
std::make_unique()<Obj>(tmp)
我该如何修复它,使其在 c++11 中可以正常工作?

Rem*_*eau 6

首先,std::make_unique()<Obj>(tmp)语法不正确,应该std::make_unique<Obj>(tmp)改为。

其次,std::make_unique()C++11 中不存在,它是在 C++14 中添加的(与std::make_shared()C++11 中确实存在的 不同)。

如果您查看 的cppreference 文档std::make_unique()它会显示一个可能的实现(经过一些细微的调整)可以应用于 C++11 代码。如果您的代码不需要担心对std::unique<T[]>数组的支持,那么最简单的实现将如下所示:

template<class T, class... 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::前缀):

make_unique<Obj>(tmp)