c++智能指针简单使用

一. 智能指针的基本作用

一句话带过:智能指针就是帮我们C++程序员管理动态分配的内存的,它会帮助我们自动释放new出来的内存,从而避免内存泄漏!

二. 一个内存泄露的例子

#include <iostream>
#include <memory>
#include <string>

class Test {
public:
    Test()
    {
        std::cout << "Test的构造函数..." << std::endl;
    }

    ~Test()
    {
        std::cout << "Test的析构函数..." << std::endl;
    }

    int getDebug()
    {
        std::cout << "just debug!" << std::endl;
        return 0;
    }

private:
    int debug = 20;
};

int main() {
    Test *test = new Test;
    test->getDebug();
    return 0;
}

终端输出:

Test的构造函数...
just debug!

为什么没有"析构"呢,内存泄露了吧,为什么呢?
因为代码中用new开辟了内存,但是程序结束时没有销毁内存,造成了内存泄露!

三. 用智能指针

#include <iostream>
#include <memory>
#include <string>

class Test {
public:
    Test()
    {
        std::cout << "Test的构造函数..." << std::endl;
    }

    ~Test()
    {
        std::cout << "Test的析构函数..." << std::endl;
    }

    int getDebug()
    {
        std::cout << "just debug!" << std::endl;
        return 0;
    }

private:
    int debug = 20;
};

int main() {
    std::shared_ptr<Test> test(new Test);
    //std::shared_ptr<Test> test;
    // test.reset(new Test);   // 释放掉智能指针托管的指针内存,并将参数指针取代之
    test->getDebug();
    return 0;
}

终端输出:

Test的构造函数...
just debug!
Test的析构函数...

可以看到,用智能指针之后,就不用手动销毁内存了,也没有内存泄露!

参考:
https://blog.csdn.net/weixin_41504987/article/details/124396989
https://zhuanlan.zhihu.com/p/526147194?utm_id=0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值