`std::unique_ptr` 是 C++11 引入的智能指针,用于管理动态分配的对象的生命周期。`unique_ptr` 确保每个动态分配的对象有且仅有一个所有者,当 `unique_ptr` 超出作用域时,它会自动释放其管理的对象。以下是 `std::unique_ptr` 的一些常见初始化方法。
### 1. 使用 `std::make_unique`
`std::make_unique` 是 C++14 中引入的函数,提供了一种安全的方式来创建 `unique_ptr`。它会自动推导类型并分配内存,避免了手动使用 `new`。
```cpp
#include <memory>
int main() {
// 使用 std::make_unique 创建 unique_ptr
auto ptr = std::make_unique<int>(42); // 创建一个指向整数的 unique_ptr
return 0;
}
```
### 2. 直接使用 `new` 运算符
可以直接使用 `new` 运算符来初始化 `unique_ptr`。这种方法需要显式地使用 `new` 关键字。
```cpp
#include <memory>
int main() {
// 直接使用 new 初始化 unique_ptr
std::unique_ptr<int> ptr(new int(42)); // 创建一个指向整数的 unique_ptr
return 0;
}
```
### 3. 初始化为空
可以初始化一个空的 `unique_ptr`,随后可以在需要时赋值。
```cpp
#include <memory></

最低0.47元/天 解锁文章
2806

被折叠的 条评论
为什么被折叠?



