首页 > 编程笔记 > C++笔记 阅读:1

C++ std::unique_ptr的用法(附带实例)

C++11 引入了 3 种智能指针,它们是 std::shared_ptr、std::unique_ptr 和 std::weak_ptr。这些智能指针提供了更安全和方便的内存管理方式,主要用于管理动态分配的对象,主要通过利用对象的析构操作来自动释放内存,以此来提高内存的安全性。

与 std::shared_ptr 不同,std::unique_ptr 不能被复制或共享,它通过独占资源的所有权来确保资源可以正确地被释放。

std::unique_ptr 是独占性的,只能有一个 std::unique_ptr 指向同一资源。当 std::unique_ptr 被销毁或转移所有权时,它会自动释放所拥有的资源。因为 std::unique_ptr 不需要维护引用计数,相比于 std::shared_ptr 更轻量。

std::unique_ptr 支持移动语义,可以通过 std::move() 将所有权从一个 std::unique_ptr 转移到另一个 std::unique_ptr,而不会对资源进行复制。

下面是 std::unique_ptr 的一个简单示例,代码如下:
#include <iostream>
#include <memory>

class Resource
{
public:
    Resource()
    {
        std::cout << "Resource acquired" << std::endl;
    }
    ~Resource()
    {
        std::cout << "Resource released" << std::endl;
    }
    void doSomething()
    {
        std::cout << "Doing something with the resource" << std::endl;
    }
};

int main()
{
    std::unique_ptr<Resource> ptr(new Resource());
    if (ptr) {
        ptr->doSomething();        // 输出 "Doing something with the resource"
    }

    // 使用 std::move 将所有权转移给另一个 std::unique_ptr
    std::unique_ptr<Resource> newPtr = std::move(ptr);
    if (newPtr) {
        newPtr->doSomething();    // 输出 "Doing something with the resource"
    }
    return 0;
}
输出结果为:

Resource acquired
Doing something with the resource
Doing something with the resource
Resource released

在这个示例中,首先创建了一个 std::unique_ptr 对象 ptr,并使用 new 关键字分配了一个资源,然后输出"Resource acquired"。接着,通过箭头操作符->调用资源的成员函数 doSomething(),输出 "Doing something with the resource"。

相关文章