C++ 标准库 - <memory>

C++14 的 std::make_unique<T>(args...) 在堆上构造 T,返回独占智能指针。离开作用域时自动 delete。

原型

template<class T, class... Args>
unique_ptr<T> make_unique(Args&&... args);

参数

  • args:转发给 T 的构造函数。

返回值

管理该对象的 unique_ptr<T>。

示例

#include <iostream>
#include <memory>

int main() {
    std::unique_ptr<int> p = std::make_unique<int>(42);
    std::cout << *p << "\n";
    return 0;
}

输出:

42

注意事项

不要再写 unique_ptr<T>(new T(...)),异常安全也更好。数组形式为 make_unique<T[]>(n)。

下一页介绍unique_ptr::get。