在程序中为了提高性能,降低程序的内存使用量。可以使用引用计数技术。
该技术的详细可以参见《More Effective C++》的条款29。
在没有使用引用计数的String类中如果写下如下语句:
String a, b, c;
a = b = c = "Hello";
a ,b,c3个对象中都有“Hello”字符串。
如果 a,b,c都指向同一个"Hello"字符串就能节省内存。
因此可以使用引用计数来对对象copy时进行(count++),对象删除时(count--),
所以在String对象中需要增加一个count变量。
使用了引用计数后的String类的声明如下:
class String {
private:
struct StringValue {
int refCount;
char *data;
StringValue(const char *initValue);
~StringValue();
};
StringValue *value;
public:
String(const char *initValue = "");
String(const String& rhs);
~String();
String& operator=(const String& rhs);
};
private:
struct StringValue {
int refCount;
char *data;
StringValue(const char *initValue);
~StringValue();
};
StringValue *value;
public:
String(const char *initValue = "");
String(const String& rhs);
~String();
String& operator=(const String& rhs);
};