c++ - Custom string class and destructors? -
i bored today , want create own little string class. 'system.string' class in .net it's split/replace/remove etc. functions , want attempt implement them.
my problem destructor. if have multiple instances of string class hold same string, of them try , delete[] same memory when destructor called??
for example:
void dosomething() { mystringclass text = "hello!"; { mystringclass text2 = text; // text2 } // text2 destroyed, char* string in memory // text points useless memory?? } am understanding right? lol.
thanks,
alex
edit:
oops, forgot include code:
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; } };
you correct -- both attempt delete [] same memory block.
you did not define copy constructor class, default one, performs shallow copy of pointer.
when text2 falls out of scope, pointer delete []d. when text1 falls out of scope, same pointer delete []d again, resulting in undefined behavior.
there number of ways around this, simplest being define copy constructor , assignment operator.
Comments
Post a Comment