C++智能指针 unique_ptr shared_ptr weak_ptr

智能指针是C++标准库提供的一种RAII(资源获取即初始化)类型,用于自动管理动态内存的生命周期,以避免内存泄漏和悬挂指针等问题。智能指针主要包括std::unique_ptrstd::shared_ptrstd::weak_ptr。以下是对这些智能指针的详细介绍以及如何使用它们。

1. std::unique_ptr

基本概念

通过这些智能指针,可以更安全、方便地管理动态分配的内存,减少内存泄漏和悬挂指针等问题。

  • 唯一所有权std::unique_ptr独占其所管理的对象,不能被复制,但可以移动。
  • 自动释放:当std::unique_ptr超出作用域时,它会自动释放所管理的对象
  • #include <iostream>
    #include <memory>
    
    struct MyStruct {
        int data;
        MyStruct(int val) : data(val) {
            std::cout << "MyStruct constructed with value: " << data << std::endl;
        }
        ~MyStruct() {
            std::cout << "MyStruct destructed with value: " << data << std::endl;
        }
    };
    
    int main() {
        // 创建std::unique_ptr管理的MyStruct实例
        std::unique_ptr<MyStruct> ptr = std::make_unique<MyStruct>(42);
    
        std::cout << "Data in MyStruct: " << ptr->data << std::endl;
    
        // 转移所有权
        std::unique_ptr<MyStruct> ptr2 = std::move(ptr);
        if (!ptr) {
            std::cout << "ptr is now nullptr" << std::endl;
        }
        std::cout << "Data in MyStruct through ptr2: " << ptr2->data << std::endl;
    
        // 自动释放内存
        return 0;
    }
    

    输出

  • MyStruct constructed with value: 42
    Data in MyStruct: 42
    ptr is now nullptr
    Data in MyStruct through ptr2: 42
    MyStruct destructed with value: 42
    

    2. std::shared_ptr

    基本概念
  • 共享所有权:多个std::shared_ptr可以共享同一个对象,当最后一个std::shared_ptr被销毁时,才会释放对象。
  • 引用计数std::shared_ptr内部维护一个引用计数,以跟踪有多少个shared_ptr共享同一个对象。
  • #include <iostream>
    #include <memory>
    
    struct MyStruct {
        int data;
        MyStruct(int val) : data(val) {
            std::cout << "MyStruct constructed with value: " << data << std::endl;
        }
        ~MyStruct() {
            std::cout << "MyStruct destructed with value: " << data << std::endl;
        }
    };
    
    int main() {
        // 创建std::shared_ptr管理的MyStruct实例
        std::shared_ptr<MyStruct> ptr1 = std::make_shared<MyStruct>(42);
    
        std::cout << "Data in MyStruct: " << ptr1->data << std::endl;
        std::cout << "Reference count: " << ptr1.use_count() << std::endl;
    
        {
            std::shared_ptr<MyStruct> ptr2 = ptr1; // 共享所有权
            std::cout << "Reference count after ptr2 creation: " << ptr1.use_count() << std::endl;
        } // ptr2超出作用域
    
        std::cout << "Reference count after ptr2 is out of scope: " << ptr1.use_count() << std::endl;
    
        // 自动释放内存
        return 0;
    }
    

    输出:

  • MyStruct constructed with value: 42
    Data in MyStruct: 42
    Reference count: 1
    Reference count after ptr2 creation: 2
    Reference count after ptr2 is out of scope: 1
    MyStruct destructed with value: 42
    

    3. std::weak_ptr

    基本概念
  • 弱引用std::weak_ptr不影响对象的引用计数,用于解决std::shared_ptr的循环引用问题。
  • 升级到std::shared_ptr:可以通过lock方法将std::weak_ptr升级为std::shared_ptr,前提是对象仍然存在。
  • #include <iostream>
    #include <memory>
    
    struct B; // 前向声明
    
    struct A {
        std::shared_ptr<B> b_ptr;
        ~A() {
            std::cout << "A is destroyed" << std::endl;
        }
    };
    
    struct B {
        std::weak_ptr<A> a_ptr; // 使用std::weak_ptr避免循环引用
        ~B() {
            std::cout << "B is destroyed" << std::endl;
        }
    };
    
    int main() {
        std::shared_ptr<A> a = std::make_shared<A>();
        std::shared_ptr<B> b = std::make_shared<B>();
    
        a->b_ptr = b;
        b->a_ptr = a;
    
        return 0;
    }
    

    输出:

  • A is destroyed
    B is destroyed
    

    在这个例子中,std::weak_ptr避免了std::shared_ptr之间的循环引用,确保了对象能够正确地被销毁。

    总结

  • std::unique_ptr:适用于独占所有权的场景,可以通过std::move转移所有权。
  • std::shared_ptr:适用于共享所有权的场景,自动管理引用计数。
  • std::weak_ptr:用于解决std::shared_ptr的循环引用问题,不影响对象的生命周期。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C++中,`unique_ptr`、`shared_ptr`、`weak_ptr`是三种常用的智能指针,用于管理动态分配的内存,避免内存泄漏和悬空指针等问题。 1. `unique_ptr`:是一种独占式智能指针,表示一个对象的所有权只能被一个`unique_ptr`持有,不能被其他指针或引用所共享。当`unique_ptr`超出作用域或被显式释放时,它所指向的对象将被自动销毁。例如: ```cpp std::unique_ptr<int> p(new int(10)); ``` 2. `shared_ptr`:是一种共享式智能指针,表示一个对象的所有权可以被多个`shared_ptr`共享。每个`shared_ptr`维护一个引用计数器,当引用计数器变为0时,它所指向的对象将被自动销毁。`shared_ptr`还支持自定义删除器,可以在对象销毁时执行特定的操作。例如: ```cpp std::shared_ptr<int> p = std::make_shared<int>(10); std::shared_ptr<int> q = p; ``` 3. `weak_ptr`:是一种弱引用智能指针,不能直接访问所指向的对象,只能通过调用`lock()`方法获得一个指向所指对象的`shared_ptr`。当`weak_ptr`所指向的对象已经被销毁时,`lock()`方法将返回一个空的`shared_ptr`。`weak_ptr`主要用于解决`shared_ptr`的循环引用问题,避免内存泄漏。例如: ```cpp std::shared_ptr<int> p = std::make_shared<int>(10); std::weak_ptr<int> q = p; std::shared_ptr<int> r = q.lock(); ``` 这些智能指针都定义在`<memory>`头文件中,并且都是模板类,可以用于管理各种类型的动态分配内存。在实际开发中,应尽量使用智能指针来管理内存,避免手动管理内存所带来的麻烦和风险。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值