第61课 智能指针类模板

本文内容来自于对狄泰学院 唐佐林老师 C++深度解析 课程的学习总结
智能指针

智能指针 的意义

现代 C++ 开发库中 最重要的类模板之一
C++ 中 自动内存管理 的主要手段
能够在 很大程序 上避开内存相关的问题

STL 中的智能指针 auto_ptr

生命周期结束时,销毁指向的内存空间
不能指向堆数组,只能指向堆对象(变量)
一片堆空间只属于一个智能指针对象
多个智能指针对象 不能指向同一片堆空间



实验代码
auto_ptr 的使用

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

using namespace std;

class Test
{
    string m_name;
public:
    /* 构造函数 */
    Test(const char *name)
    {
        cout << "Hello, " << name << "." << endl;
        m_name = name;
    }
    void print()
    {
        cout << "I' m" << m_name << endl;
    }
    ~Test()
    {
        cout << "Goodbye, " << m_name << endl;
    }
};

int main()
{
    auto_ptr<Test> pt(new Test("lzg"));

    cout << "pt = " << pt.get() << endl;

    pt->print();

    cout << endl;

    auto_ptr<Test> pt1(pt);

    cout << "pt = " << pt.get() << endl;
    cout << "pt1 = " << pt1.get() << endl;

    pt1->print();

    return 0;
}

运行结果:
在这里插入图片描述

实验结果:STL 库中的 auto_ptr 智能指针无需手动释放堆内存,pt 和 pt1 完成了内存管理权转移

下面我们来自己来编写一个智能指针类模板
SmartPointer.h

#ifndef _SAMRTPOINTER_H_
#define _SAMRTPOINTER_H_

template <typename T>
class SmartPointer
{
	T *mp;
public:
	SmartPointer(T *p=NULL)
	{
		mp = p;
	}

	SmartPointer(const SmartPointer<T>& obj)
	{
		mp = obj.mp;
		const_cast<SmartPointer<T>&>(obj).mp = NULL;
	}

	SmartPointer<T>& operator = (const SmartPointer<T>& obj)
	{
		if(this != &obj)
		{
			delete mp;
			mp = obj.mp;
			const_cast<SmartPointer<T>&>(obj).mp = NULL;
		}

		return *this;
	}

	T* operator -> ()
	{
		return mp;
	}

	T& operator * ()
	{
		return *mp;
	}

	bool isNull()
	{
		return (mp == NULL);
	}

	T* get()
	{
		return mp;
	}

	~SmartPointer()
	{
		delete mp;
	}
};

#endif

将上次实验 main 中的 auto_ptr 换成我们自己写的 SmartPointer,
在这里插入图片描述
运行结果:
在这里插入图片描述

实现结果,两次的运行结果一模一样,说明我们成功的实现了智能指针类模板。





小结

智能指针 C++ 中 自动内存管理 的主要手段
智能指针在各种平台上都有不同的表现形式
智能指针能够 尽可能的避开 内存相关的问题
STL 和 QT 中都提供了对智能指针的支持

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lzg2021

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值