首页 > 解决方案 > 如何在 c++11 中使用 make_unique?

问题描述

我收到以下错误:

“make_unique”不是“std”的成员

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

标签: c++unique-ptr

解决方案


首先,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)...));
}

然后你可以使用(不带std::前缀):

make_unique<Obj>(tmp)


推荐阅读