std::make_unique
是 C++14 中引入的一个函数模板,它的作用是创建一个
std::unique_ptr
智能指针,该指针指向一个新的、由给定的参数初始化的、指定类型的对象。
使用
std::make_unique
的优势在于,它可以推导出智能指针所指向的对象的类型,因此可以省略掉对象类型的显式指定。这对于简化代码和减少可能的错误都有很大的帮助。
下面是一个使用
std::make_unique
创建指向一个新的
std::vector
的智能指针的示例:
#include <memory>
#include <vector>
int main()
auto p = std::make_unique<std::vector<int>>();
return 0;
注意:如果你的编译器不支持 C++14,则无法使用 std::make_unique
。在这种情况下,你可以使用以下方法创建 std::unique_ptr
:
#include <memory>
#include <vector>
template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
int main()
auto p = make_unique<std::vector<int>>();
return 0;
这样就可以使用类似于 std::make_unique
的方法创建智能指针了。