C++ 智能指针模板类(廿六)--自动内存管理

本文介绍了C++中三种智能指针(auto_ptr, unique_ptr, shared_ptr)的基本用法及注意事项。通过示例展示了不同智能指针的特点,如auto_ptr的深复制问题、unique_ptr的不可赋值特性以及shared_ptr的引用计数机制。

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



#include <memory.h>

using namespace std;

class Done {
    
    string myS;
public:
    Done(const string &s):myS(s){  };
    
    void Doit(){ cout << myS << endl; };
    
    
};



int main(int argc, const char * argv[]) {

    /**
     * 三种智能指针语法 
     * 对应头文件 memory.h
     * new double 返回指针指向新分配内存块(形参)
     * 删除了 delete
     * new[] 不能使用 auto_ptr和shared_ptr
     * new、new[] unique_ptr 都可以处理
     */
    //1、auto_ptr 如果两个智能指针相互赋值,可能崩溃,应该用深复制
    auto_ptr<double> ap_d(new double(20.1f));
    double t = *ap_d;
    cout << "double =" << t << endl;
    
    auto_ptr<string> ap_s(new string("dsfs"));
    auto_ptr<string> ap_s2(new string("dsfs2"));
    string s(*ap_s);
    cout << "string =" << s << endl;
    ap_s2 = ap_s;  //不警告
    
    
    //2、unique_ptr 如果两个智能指针相互赋值,首先编译错误
    unique_ptr<double> up_d(new double(30));
    unique_ptr<string> up_s(new string("unique_ptr"));
    unique_ptr<string> up_s2(new string("unique_ptr2"));
    //up_s2 = up_s;  语法警告了
    up_s2 = move(up_s);
    
    
    
    //3、shared_ptr 适合多个对象指向同一指针
    shared_ptr<double> sp_d(new double(40.2f));
    shared_ptr<string> sp_s(new string("shared_ptr"));
    shared_ptr<string> sp_s2(new string("shared_ptr2"));
    sp_s2 = sp_s;
    
    
    //例子
    {
        auto_ptr<Done> ap_D(new Done("123456"));
        ap_D->Doit();
    }
    
    {
        unique_ptr<Done> up_D(new Done("asdfg"));
        up_D->Doit();
    }
    
    {
        shared_ptr<Done> sp_D(new Done("nbvcx"));
        sp_D->Doit();
    }
    
    
    
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值