当类里面有指针对象时,进行简单赋值的浅拷贝,两个对象指向同一块内存,存在崩溃的问题!为了解决这个问题,我们可以采用引用计数。
在引用计数中,每一个对象负责维护对象所有引用的计数值。当一个新的引用指向对象时,引用计数器就递增,当去掉一个引用时,引用计数就递减。当引用计数到零时,该对象就将释放占有的资源。
#include<iostream>
#include<Windows.h>
#include<string.h>
using namespace std;
class String
{
public:
String(const char* str = "")
:_str(new char[strlen(str) + 1])
{
strcpy(_str, str);
++_GetRefCount ;
}
String(String& s)
:_str(s._str)
{
++_GetRefCount;
}
String& operator=(const String&s)
{
if (this != &s)
{
this->~String();
_str = s._str;
++_GetRefCount;
}
return*this;
}
~String()
{
_Release();
}
private:
void _Release()
{
if (--_GetRefCount == 0)
{
delete[] _str;
cout << "delete" << endl;
}
}
friend ostream& operator<<(ostream& os, const String& s)
{
os << s._str;
return os;
}
private:
char* _str;
int _GetRefCount;//引用计数
};
void Test1()
{
String s1("qwer");
String s2(s1);
cout << "s1:" << s1 << endl;
cout << "s2:" << s2 << endl;
String s3;
s3 = s1;
cout << "s3:" << s3 << endl;
}
int main()
{
Test1();
system("pause");
return 0;
}