跳到主要内容
版本:Next

make_unique

std::make_unique 是 C++14 引入的工具函数,用于高效地创建 std::unique_ptr 对象。它在 C++14 之前属于明显的"标准库遗漏"——std::make_shared 在 C++11 就已存在,而 make_unique 直到 C++14 才被补上。

头文件与基本特征

#include <memory>
特征说明
作用在堆上构造对象并返回 unique_ptr
异常安全是,避免裸 new 在函数调用中的异常安全问题
代码简洁避免重复写类型名
性能与手写 new 一致,无额外控制块(不同于 make_shared

基本用法

#include <iostream>
#include <memory>

struct Point {
int x, y;
Point(int x_, int y_) : x(x_), y(y_) {}
};

int main() {
auto p1 = std::make_unique<int>(42);
auto p2 = std::make_unique<Point>(10, 20);

std::cout << *p1 << '\n';
std::cout << p2->x << ", " << p2->y << '\n';

return 0;
}

对比 C++11 的写法:std::unique_ptr<int>(new int(42))——在 C++14 中直接用 make_unique 更短且更安全。

与 make_shared 的区别

方面make_uniquemake_shared
引入版本C++14C++11
内存分配一次分配(对象)一次分配(对象 + 控制块)
自定义删除器不支持不支持
数组支持C++14 支持 make_unique<T[]>C++17+ 支持

使用注意

  1. 无法在 make_unique 中指定自定义删除器,需要时仍要手动构造 unique_ptr
  2. make_uniquenew 性能相同,不像 make_shared 有额外合并分配的优化。
  3. 优先用 make_unique,只在需要自定义删除器或接管已有裸指针时才手写 unique_ptr

小结

std::make_unique 虽简单,但填补了 C++11 的空白行,使 unique_ptr 的创建和 shared_ptr 一样便利。从现在起,新建 unique_ptr 时默认使用它。