#pragma once class String { public: String(char* pStr); String(const String& param); virtual ~String(); String& operator=(const String& param); private: struct StringValue { StringValue(char* pStr); ~StringValue(); // nested class只需要提供 构造和析构 函数 其余函数由外部类提供 /*StringValue(const StringValue& param); StringValue& operator=(const StringValue& param);*/ char* pValue; int refCount; }; StringValue* value; }; #include "stdafx.h" #include "string.h" #include <string.h> #include <stdlib.h> // 内部类 构造函数 负责将refcount置1 并且分配实际内存 String::StringValue::StringValue(char* pStr) : refCount(1) { pValue = new char[strlen(pStr)+1]; strcpy(pValue, pStr); } // 内部类 析构函数 直接释放 不需要考虑refcount 外部类会进行考虑 String::StringValue::~StringValue() { delete [] pValue; } // 外部类 构造函数 不需要考虑refcount 因为内部类构造函数已经考虑了 // 需要调用内部类构造函数 String::String(char* pStr) : value(new StringValue(pStr)) { } // 外部类 析构函数 需要考虑refcount // 需要改变指针 String::String(const String ¶m) : value(param.value) { ++value->refCount; } // 外部类析构函数 需要考虑refcount refcount为0 删除实际对象 String::~String() { if(--value->refCount == 0) delete value; } String& String::operator =(const String ¶m) { // 1 相等 直接返回 if(this->value == param.value) return *this; // 2 删除原来指向 (需要的时候删除实际内存) if(-- this->value->refCount == 0) delete this->value; // 3 改变原来指向 this->value = param.value; // ref count++ ++ this->value->refCount; return *this; }