C++(std::unique_ptr)

发布时间 2023-12-11 16:52:59作者: 做梦当财神

std::unique_ptr 是 C++ 标准库中的一种智能指针,用于管理动态分配的内存。它是一种独占拥有权(exclusive ownership)的智能指针,保证同一时刻只有一个 std::unique_ptr 指向特定的资源。当 std::unique_ptr 被销毁时,它所拥有的资源也会被释放。

以下是 std::unique_ptr 的基本用法和一些注意事项:

基本用法:

#include <iostream>
#include <memory>

int main() {
    // 使用 std::make_unique 创建 std::unique_ptr,拥有一个动态分配的整数
    std::unique_ptr<int> uniqueInt = std::make_unique<int>(42);

    // 使用指针操作内存
    std::cout << "Value: " << *uniqueInt << std::endl;

    // uniqueInt 指针拥有独占权,不能直接赋值给其他 unique_ptr
    // std::unique_ptr<int> anotherUniqueInt = uniqueInt;  // 编译错误

    // 通过 std::move 转移所有权
    std::unique_ptr<int> anotherUniqueInt = std::move(uniqueInt);

    // uniqueInt 现在为空,不再拥有资源
    if (!uniqueInt) {
        std::cout << "uniqueInt is null" << std::endl;
    }

    // anotherUniqueInt 持有资源
    std::cout << "Value: " << *anotherUniqueInt << std::endl;

    // 在块的末尾,anotherUniqueInt 被销毁,其拥有的资源也被释放

    return 0;
}

注意事项和特性:

  1. 独占拥有权: std::unique_ptr 保证同一时刻只有一个指针拥有资源,这避免了共享指针的引用计数和可能的资源竞争。
  2. 移动语义: std::unique_ptr 支持移动语义,通过 std::move 可以转移拥有权。这使得在函数调用中传递 std::unique_ptr 更高效。
  3. 不能直接复制: std::unique_ptr 不能直接进行复制,因为它是独占拥有权的。要进行所有权的转移,需要使用 std::move
  4. 自动释放资源:std::unique_ptr 超出作用域时,它所拥有的资源会被自动释放。这避免了显式的 delete 操作。
  5. 不适合共享所有权: 如果需要共享所有权,应该使用 std::shared_ptr
  6. 适用于动态分配数组: std::unique_ptr 也可用于动态分配数组。例如,std::unique_ptr<int[]> arr = std::make_unique<int[]>(5);

在现代 C++ 中,推荐使用 std::unique_ptr 来管理动态分配的内存,以提高代码的安全性和可读性。