学习C++:智能指针

1.什么是智能指针

C++智能指针是包含重载运算符的类,其行为像常规指针,但智能指针能够及时妥善地销毁动态分配的数据,并实现了明确的对象生命周期,因此更有价值。
常规指针存在的问题
C++在内存分配、释放和管理方面提供了全面的灵活性;另一方面,它有可能产生与内存相关的问题,比如动态分配的对象没有正确地释放将导致内存泄漏。
智能指针的作用
智能指针的行为类似常规指针,但通过重载的运算符和析构函数确保动态分配的数据能够及时地销毁,从而提供了更多有用的功能。
smart_pointer spDate = mObject.GetData ();
spData->Display();
(*spData).Display();

2.智能指针的实现

智能指针类重载了解除引用运算符(*)和成员选择运算符(->),使得可以像常规指针那样使用它们。下面演示一个简单智能指针类的实现:

template <typename T>
class smart_pointer
{
private:
	T* m_pRawPointer;
public:
	smart_pointer(T* pData) : m_pRawPointer(pData){}   //构造函数
	~smart_pointer(){delete pData;}; //析构函数
	smart_pointer(const smart_pointer & anotherSP); //复制构造函数
	smart_pointer& operator= (const smart_pointer & anotherSP);
	T& operator*() const
	{
		return *(m_pRawPointer);
	}
	T* operator() const
	{
		return m_pRawPointer;
	}
};

3.智能指针类型

智能指针决定在复制和赋值时如何处理内存资源。智能指针的分类实际上就是内存资源管理策略的分类。可分为以下几类:
深复制、写时复制、引用计数、引用链接、破坏性复制。
深复制
在实现深复制的智能指针中,每个智能指针实例都保存一个它管理的对象的完整副本。每当智能指针被复制时,将复制它指向的对象。每当智能指针离开作用域时,将释放它指向的内存。
虽然基于深复制的智能指针看起来并不比按值传递对象优越,但在处理多态对象时,其优点将显示出来。
下面演示使用基于深复制的智能指针能将多态对象作为基类对象进行传递。

template<typename T>
class deepcopy_smart_pointer
{
private:
	T* m_pObject;
public:
	deepcopy_smart_pointer(const deepcopy_smart_pointer& source)  //复制构造函数
	{
		m_pObject = source->Clone();
	}
	deep_smart_pointer& operator=(const deepcopy_smart_pointer& source)  //复制赋值运算符
	{
		if(m_pObject)
			delete m_pObject;
		m_pObject=source->Clone();
	}
};

4.使用std::unique_ptr

std::unique_ptr 是一种简单的智能指针,但其复制构造函数和赋值运算符被声明为私有的,因此不能复制它,即不能将其按值传递给函数,也不能将其赋值给其他指针。
unique_ptr是C++11新增的,与auto_ptr稍微不同,因为它不允许复制和赋值。使用std::unique_ptr,必须包含头文件:

#include <memory>

下面将演示如何使用最简单的智能指针:

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

class Fish
{
public:
	Fish(){cout<<"构造函数"<<endl;}
	~Fish(){cout<<"析构函数"<<endl;}
	void Swim() const {cout<<"Fish swim in watar"<<endl;}
};
void MakeFishSwim(const unique_ptr<Fish>& inFish)
{
	inFish->Swim();
}
int main()
{
	unique_ptr<Fish> smartFish(new Fish);
	smartFish->Swim();
	MakeFishSwim(smartFish);
	return 0;
}
发布了12 篇原创文章 · 获赞 13 · 访问量 615

猜你喜欢

转载自blog.csdn.net/wjinjie/article/details/104295470