The answer is that you have to release the memory because if you didn't then it would be lost, since you are reusing the pointer for a new allocation. Anyway, if you are learning about operators, it is common to write operator=
in terms of copy construction + no-throw swap:
class MyString {
char* str;
int len;
public:
MyString( const MyString& rhs ) : str( new char[ rhs.len ] ), len( rhs.len ) {
memcpy( str, rhs.str, len );
}
~MyString() {
delete str;
}
friend void swap( MyString & lhs, MyString & rhs ) throw() {
using std::swap;
swap( lhs.str, rhs.str );
swap( lhs.len, rhs.len );
}
MyString& operator=( MyString rhs ) { //note: by value
swap( *this, rhs );
return *this;
}
};
Note that the operations that are performed are the similar. Now the differences:
There is less overall code. Any operation that needs to be performed while copying will be implemented only in the copy constructor, the assignment operator borrows that code.
There is no need to check for self-assignment, as the copy is performed before the old memory is released
This implementation is exception safe: If there is a problem while allocating memory (or any other operation in the copy constructor) the operation has no side effects
Self assignment is less performant, as new memory is allocated, then copied and released. But assignment from temporaries (rvalue expressions) will be faster, as the compiler can elide the copy. Still performance should only be considered when and if measurements point at a bottleneck in the code.