I recently compiled a string class (not my class, I must add, the one from SAMS 21 days)
I won't regurgitate the whole thing here, as my question is only specific to a certain section of the code, I'll try to give all that's needed.
Firstly, it has the private member variables
it has one overloaded assignment operator, which is as follows ( I've only written the definition here )Code:unsigned short len char* itsString String( unsigned short )
So far so good. Then in the main function it does this.Code:String& String::operator =(const String & rhs) { if( this == &rhs ) return *this; delete[] itsString; len = rhs.getLength(); for( unsigned short i = 0; i<len; i++ ) itsString[i] = rhs[i]; itsString[len] = '\0'; return *this; }
Now unless I'm mistaken, the argument for the assignment operator being used in this case is a C-string literal, and not a "String" as expected by our overloaded assignment operator. So here the compiler will make it's own assignment operator correct? Either way it compiles but when I run the program the debugger pops up and tells me there is a problem, and points to the destructor, which looks like thisCode:char* temp = "Hello World"; s1 = temp //s1 has already been declared as a string
For convenience, here's the message which pops up, not that it's terribly interesting.Code:String::~String() { delete [] itsString; len = 0; }
http://www.stonehambey.com/debugString.jpg
My initial thought was that the compiler generated assignment operator for C style strings didn't assign the private member variables properly and that is why there was a problem when the destructor on it is called when the program closes.
I tried writing my own additional assignment operator, which looked something like this
But I'm still getting problems when debugging the program (of course it could be I haven't written the second assignment operator correctly ;) )Code:String& String::operator =(const char * rhs) { if( itsString == rhs ) return *this; delete[] itsString; len = strlen( rhs ) + 1; for( unsigned short i = 0; i<len; i++ ) itsString[i] = rhs[i]; itsString[len] = '\0'; return *this; }
I'm pretty sure it's got something to do with that part of the main program, since when I comment it out it works fine, but I'm just not sure what.
Any advice or help would be greatly appreciated :)
Regards,
Stonehambey



LinkBack URL
About LinkBacks



