在智能指针中,auto_ptr已经使用的越来越少了,特别是在C++11中,它已经被shared_ptr取代,原因主要有以下两点:
1. auto_ptr不能保留指针所有权
class Test
{
public:
Test(int m) : m_test(m) {}
~Test();
public:
int m_test;
};
/*********************/
void fun(auto_ptr<Test> p1)
{
cout << p1->m_test << endl;
}
/*******************/
void main()
{
auto_ptr<Test> p(new Test(5));
fun(p);
cout << p->m_test << endl;//出错
}
上述代码中,主函数中的p作为参数传递给p1,此时p也就将所有权交给了p1,p1在fun函数执行完后释放内存块,而此时的p什么都没了,所以不再有访问内存数据的权力了。
2.不能能指向对象数组
这个缺点使得它不能和new[]一起使用
void main()
{
auto_ptr<Test> p(new Test[5]);
}
上述代码运行时会出现一个问题,当auto_ptr离开作用域时,会默认调用delete释放内存空间,对于一个对象显然是没有问题的,但是这里的p指向的是一个对象组,需要用delete[]来释放内存,而如果继续用delete就会有问题。
基于以上两点,在实际中我们采用shared_ptr替代auto_ptr的功能。因为shared_ptr有一个引用计数功能。话不多说,下面直接给出shared_ptr的实现代码:
/****这里仅给出核心部分的代码********/
#include<iostream>
using namespace std;
template<class T>
class shared_ptr
{
private:
T* m_ptr;
unsigned int shared_count;
public:
shared_ptr(T* ptr) : m_ptr(ptr), shared_ptr{}
~shared_ptr() {deconstruct();}
void deconstruct()
{
if(shared_count == 1)
{
delete m_ptr;
m_ptr = NULL;
}
count--;
}
T* operator&() {return m_ptr;}
T& operator*() {return *m_ptr;}
//拷贝构造函数
shared_ptr(shared_ptr& sp) : m_ptr(sp.m_ptr), shared_count(sp.shared_count)
{
shared_count++;
}
//赋值运算符
shared_ptr& operator=(shared_ptr& sp)
{
sp.shared_count++;
deconstruct();
m_ptr = sp.m_ptr;
shared_count = sp.shared_count;
return *this;
}
};
部分摘自:C++11智能指针