c++ - 如何在 c++11 中使用 make_unique?
问题描述
我收到以下错误:
“make_unique”不是“std”的成员
当它编写以下代码时:
std::make_unique()<Obj>(tmp)
如何修复它在 c++11 中可以正常工作?
解决方案
首先,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)
推荐阅读
- opengl - OpenGL - 将多个图像加载到纹理
- database - 如何从问号绑定 pdo 键和值?
- sql - JOIN 中的条件 IIF
- qt - 我们可以在 QVideoWidget 中包含并显示其他一些小部件吗?
- html - 将自动高度设置为容器时,它将页面移动
- c# - 读取数据表并在行异步 c# 中执行循环
- javascript - 如何将内容从一个对象添加到另一个对象?
- dart - 如果我尝试读取不存在的文件,会引发什么异常?
- c++ - 将我的全局变量放在 Microsoft Visual Studio Form 中的什么位置?
- c - ollydbg 中有许多“printf”,但 a.exe 中只有一个“printf”