/*#include<iostream>
using namespace std;
#include<string>
template<class T>
class String
{
public:
String()
{
_str = new char[1];
_str[0] = '\0';
}
String(const char *str)
{
_str = new char[strlen(str) + 1];
strcpy(_str, str);
}
String(const String &str)
{
_str = new char[strlen(str._str) + 1];
strcpy(_str, str._str);
}
String &operator = (const String &str)
{
if (str != this)
delete[]_str;
_str = new char[strlen(str._str) + 1];
strcpy(_str, str._str);
}
~String()
{
if (_str!=NULL)
{
delete[]_str;
}
}
void showStr()
{
cout << this->_str << endl;
}
private:
T *_str;
};
void main()
{
String<char> s1;
String<char> s2("abcrrr");
String<char> s3(s2);
String<char> s4 = s3;
s4.showStr();
}
*/
/*简洁版
#include<iostream>//防止开辟的空间没有释放,程序在delete之前return了。类构造的对象一定会调用析构函数。这就是智能指针。
using namespace std;
template <class T>
class autoptr
{
public:
autoptr(T *p) :_ptr(p)
{
}
~autoptr()
{
if (_ptr)
{
delete _ptr;
}
}
autoptr(autoptr<T>&a) :_ptr(a._ptr)
{
a._ptr = NULL;
}
T &operator *()
{
return *_ptr;
}
private:
T *_ptr;
//autoptr (autoptr<T>&a);//放置拷贝构造。防止多次的析构,加入引用计数count。如果count>0,每次调用析构函数时候,只把count——当count=0,时候再调用析构函数。};
};
void test()
{
int *p = new int(1);
autoptr<int>ap1(p);
autoptr<int>ap2(ap1);
autoptr<int>ap3(p);//多次析构这个p;会死机。
}
int main()
{
test();
return 0;
}
//share ptr;引用计数版
template<class T>
class SmartPtr
{
SmartPtr(T *p)
{
_ptr = p;
pcount = new int(1);//开辟空间
}
SmartPtr(SmartPtr&s)
{
_ptr = s._ptr;
pcount = s.pcount;//增加引用计数
++pcount[0];
}
SmartPtr &operrator = (const &s)
{
if (&s != this&&s._ptr!=_ptr)
{
if (--pcount[0] == 0 && _ptr)
{
delete _ptr;
delete pcount;//释放指针
}
_ptr = s._ptr;
pcount = s.pcount;//增加引用计数
++pcount[0];
}
}
T *operrator->()
{
return _ptr;
}
T *operrator*()//重载指针可以用指针方式
{
return *_ptr;
}
~SmartPtr()
{
if (--(*pcount) == 0 && _ptr)//当引用计数为0,调用析构函数。
{
delete _ptr;
delete pcount;
}
}
private:
T *_ptr;
int *pcount;
};
·