C++程序设计中使用堆内存是非常频繁的操作,堆内存的申请和释放都由程序员自己管理。程序员自己管理堆内存可以提高了程序的效率,但是整体来说堆内存的管理是麻烦的,C++11中引入了智能指针的概念,方便管理堆内存。使用普通指针,容易造成堆内存泄露(忘记释放),二次释放,程序发生异常时内存泄露等问题等,使用智能指针能更好的管理堆内存。
理解智能指针需要从下面三个层次:
- 从较浅的层面看,智能指针是利用了一种叫做RAII(资源获取即初始化)的技术对普通的指针进行封装,这使得智能指针实质是一个对象,行为表现的却像一个指针。
- 智能指针的作用是防止忘记调用delete释放内存和程序异常的进入catch块忘记释放内存。另外指针的释放时机也是非常有考究的,多次释放同一个指针会造成程序崩溃,这些都可以通过智能指针来解决。
- 智能指针还有一个作用是把值语义转换成引用语义。C++和Java有一处最大的区别在于语义不同,在Java里面下列代码:
Animal a = new Animal();
Animal b = a;
你当然知道,这里其实只生成了一个对象,a和b仅仅是把持对象的引用而已。但在C++中不是这样,
Animal a;
Animal b = a;
这里却是就是生成了两个对象。
下面是一个简单智能指针的demo。智能指针类将一个计数器与类指向的对象相关联,引用计数跟踪该类有多少个对象共享同一指针。每次创建类的新对象时,初始化指针并将引用计数置为1;当对象作为另一对象的副本而创建时,拷贝构造函数拷贝指针并增加与之相应的引用计数;对一个对象进行赋值时,赋值操作符减少左操作数所指对象的引用计数(如果引用计数为减至0,则删除对象),并增加右操作数所指对象的引用计数;调用析构函数时,构造函数减少引用计数(如果引用计数减至0,则删除基础对象)。智能指针就是模拟指针动作的类。所有的智能指针都会重载 -> 和 * 操作符。智能指针还有许多其他功能,比较有用的是自动销毁。这主要是利用栈对象的有限作用域以及临时对象(有限作用域实现)析构函数释放内存。
#include <iostream>
#include <memory>
template<typename T>
class SmartPointer
{
public:
SmartPointer(T* ptr = nullptr)
:ptr(ptr)
{
if (ptr)
count = new size_t(1);
else
count = new size_t(0);
}
SmartPointer(const SmartPointer& ptr)
{
if (this != &ptr)
{
this->ptr = ptr.ptr;
this->count = ptr.count;
(*this->count)++;
}
}
SmartPointer& operator=(const SmartPointer& ptr)
{
if (this->ptr == ptr.ptr)
return *this;
if (this->ptr)
{
(*this->count)--;
if (this->count == 0)
{
delete this->ptr;
delete this->count;
}
}
this->ptr = ptr.ptr;
this->count = ptr.count;
(*this->count)++;
return *this;
}
T& operator*()
{
assert(this->ptr == nullptr);
return *(this->ptr);
}
T* operator->()
{
assert(this->ptr == nullptr);
return this->ptr;
}
~SmartPointer()
{
(*this->count)--;
if (*this->count == 0)
{
delete this->ptr;
delete this->count;
}
}
size_t use_count()
{
return *this->count;
}
private:
T* ptr;
size_t* count;
};
int main()
{
SmartPointer<int> sp(new int(10));
SmartPointer<int> sp2(sp);
SmartPointer<int> sp3(new int(20));
sp2 = sp3;
std::cout << sp.use_count() << std::endl;
std::cout << sp3.use_count() << std::endl;
}
参考:
- http://www.cnblogs.com/Solstice/archive/2011/08/16/2141515.html
- http://www.cnblogs.com/jiayayao/archive/2016/12/03/6128877.html
- http://blog.csdn.net/pi9nc/article/details/12227887
- http://blog.csdn.net/mmzsyx/article/details/8090849
- http://blog.csdn.net/shanno/article/details/7363480