string类和智能指针(简洁版)和shareptr简洁版代码实现

/*#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 (&!= this&&s._ptr!=_ptr)

{

if (--pcount[0] == 0 && _ptr)

{

delete _ptr;

delete pcount;//释放指针

}

_ptr = s._ptr;

pcount = s.pcount;//增加引用计数

++pcount[0];

}

 

}

*operrator->()

{

 

return _ptr;

 

}

*operrator*()//重载指针可以用指针方式

{

return *_ptr;

 

}

 

~SmartPtr()

 

{

if (--(*pcount) == 0 && _ptr)//当引用计数为0,调用析构函数。

{

 

delete _ptr;

delete pcount;

}

}

private:

*_ptr;

int *pcount;

 

};

 

 

 

 

· 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值