C++资源管理:智能指针unique_ptr和shared_ptr

本文介绍了C++中的两种智能指针:unique_ptr和shared_ptr,并通过具体示例展示了它们的应用场景。unique_ptr适用于拥有唯一所有权的情况,而shared_ptr则用于多个对象共享同一资源的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、介绍

memory头文件中提供了unique_ptr和shared_ptr两种智能指针来避免内存泄漏,二者都基于RAII(栈上临时对象的生命周期由程序自动管理、临时对象离开其作用域会自动调用析构函数)来管理另一个对象的生命周期。区别在于unique_ptr所管理的对象所属关系是唯一的;而shared_ptr所管理的对象的所属关系可以和其它同类shared_ptr共享、当最后一个管理这个对象的shared_ptr被销毁时才会调用对象的析构函数。

二、使用场合

1.需要共享某一个对象的时候,使用shared_ptr
2.不知道对象的具体类型,需要藉助指针来利用多态性的时候,使用unique_ptr
3.具备多态性的共享对象通常需要使用shared_ptr

三、示例


```cpp
#include <iostream>
#include <memory>
using namespace std;

class Parent
{
public:
    Parent(int id):m_id(id) {}
    virtual void hello(){ cout<<"Hello parent "<<m_id<<endl; }
    virtual ~Parent(){ cout<<"Bye parent "<<m_id<<endl; }
protected:
    int m_id;
};

class Kid : public Parent
{
public:
    Kid(int id):Parent(id) {}
    void hello() { cout<<"Hello kid "<<m_id<<endl; }
    ~Kid() { cout<<"Bye kid "<<m_id<<endl; }
};

template <typename T>
class RaiiExample
{
public:
    RaiiExample(T* ptr ) :obj(ptr) {}
    T* get(){ return obj; }
    ~RaiiExample()
    {
        if(obj)
        {
            delete obj;
            obj = nullptr;
        }
    }

private:
    T* obj;
};

using  AutoTest = unique_ptr<Parent> ;

AutoTest testFunction(int id)
{
    AutoTest test{ new Kid(id)};
    return test;
}


int main()
{
    for(int i = 0 ; i < 3 ; i++)
    {
        testFunction(i)->hello();
        RaiiExample<Kid> a{new Kid(i*2)};
        a.get()->hello();
    }
    return 0;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值