在程序中为了提高性能,降低程序的内存使用量。可以使用引用计数技术。

该技术的详细可以参见《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);

};

相关文章:

  • 2022-12-23
  • 2021-08-20
  • 2021-04-06
  • 2021-05-22
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-06-01
  • 2021-08-21
  • 2021-07-14
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案