1. 智能指针
C++由于没有Java一样的内存回收机制,需要程序员自己delete new的内存,否则的话会发生内存泄露的情况。
智能指针便是为了解决这个问题。智能指针可自动释放新申请的内存,如同JAVA的GC一样。
详细的参考:http://blog.youkuaiyun.com/hackbuteer1/article/details/7561235
下面是示例代码:
template<class T> class HasPtr;
template<class T>
class U_Ptr
{
friend class HasPtr<T>;
T *ip;
size_t use; // 使用计数
U_Ptr(T *p) : ip(p), use(1)
{
cout << "U_Ptr() called!" << endl;
}
~U_Ptr()
{
delete ip;
cout << "~~U_Ptr() called!" << endl;
}
};
template<class T>
class HasPtr
{
public:
HasPtr(T *p, int i) : ptr(new U_Ptr<T>(p)), val(i)
{
cout << "(" << val << ")" << "HasPtr() called!" << endl;
}
~HasPtr()
{
cout << "(" << val << ")" << "~~HasPtr() called!" << endl;
ptr->use--; // 减少引用的时候,计数减1
if (ptr->use == 0) // 不再引用的时候,释放内存
{
delete ptr;
}
}
// 复制构造函数
HasPtr<T>(const HasPtr<T> &other) : ptr(other.ptr), val(other.val)
{
ptr->use++;
cout << "(" << val << ")" << "HasPtr(HastPtr&) called!" << endl;
}
// 赋值运算符重载
HasPtr<T>& operator=(const HasPtr<T>&);
T* GetObj() const
{
return ptr->ip;
}
int GetCount() const
{
return ptr->use;
}
private:
U_Ptr<T> *ptr; // 智能指针
int val; // 额外的成员变量
};
template<class T>
HasPtr<T> & HasPtr<T>::operator=(const HasPtr<T> & rhs)
{
cout << "(" << this->val<< "->" << rhs.val << ") " << "operator= called!" << endl;
// 右操作数增加指针指向,计数加1
rhs.ptr->use++;
// 左操作数不再指向原先的指针,计数减1
if (--ptr->use == 0)
{
delete ptr;
}
ptr = rhs.ptr;
val = rhs.val;
return *this;
}
void TestSmartPointer()
{
string *pStr = new string("this is my string");
int extVal = 1024;
HasPtr<string> ptr(pStr, extVal); // 构造函数, pstr一定要是new/malloc/realloc/zalloc出来的指针
cout << "Use: " << ptr.GetCount() << endl;
HasPtr<string> ptr2(ptr); // 复制构造函数
cout << "Use: " << ptr.GetCount() << endl;
HasPtr<string> ptr3(new string("ptr3 string"), 512);
ptr3 = ptr; // 赋值操作符
cout << "Use: " << ptr.GetCount() << endl;
}
运行结果:
2. boost的智能指针
STL和boost的智能指针有std::auto_ptr、boost::scoped_ptr、boost::shared_ptr、boost::scoped_array、boost::shared_array、boost::weak_ptr、boost:: intrusive_ptr
详细的参考:http://blog.youkuaiyun.com/xt_xiaotian/article/details/5714477
下面是我的测试代码:
class Shared
{
public:
Shared(string str) : m_strNo(str)
{
std::cout << m_strNo << " ctor() called"<<std::endl;
}
Shared(const Shared & other)
{
std::cout << m_strNo << " copy ctor() called"<<std::endl;
}
~Shared()
{
std::cout << m_strNo << " dtor() called"<<std::endl;
}
private:
string m_strNo;
};
void TestSmart()
{
typedef boost::shared_ptr<Shared> SharedSP;
SharedSP sp1(new Shared("Sp1")); // 构造函数
cout << "Use count: " << sp1.use_count() << endl;
SharedSP sp2(sp1); // 复制构造函数
cout << "Use count: " << sp1.use_count() << endl;
SharedSP sp3(new Shared("Sp3"));
sp3 = sp1; // sp3的对象指针将释放内存
cout << "Use count: " << sp1.use_count() << endl;
}
运行结果: