今日は退屈だったので、自分の小さなストリング クラスを作成したいと思います。.Net の 'System.String' クラスは、Split/Replace/Remove などの機能が非常に気に入っており、それらを実装したいと考えています。
しかし、私の問題はデストラクタです。同じ文字列を保持する文字列クラスの複数のインスタンスがある場合、デストラクタが呼び出されたときに、それらすべてが同じメモリを削除しようとしますか??
例えば:
void DoSomething() {
MyStringClass text = "Hello!";
{
MyStringClass text2 = text;
// Do something with text2
} // text2 is destroyed, but so is the char* string in memory
// text now points to useless memory??
}
私はこれを正しく理解していますか?笑。
ありがとう、
アレックス
編集:
おっと、コードを含めるのを忘れていました:
class string {
unsigned int length;
char* text;
public:
string() : length(0), text(NULL) { }
string(const char* str) {
if (!str) throw;
length = strlen(str);
text = new char[length];
memcpy(text, str, length);
}
~string() {
delete[] text;
}
};