Im reading a book about c++ and in the "Copy Control" section the author teach us to write the operator=
in a class telling us that we have to be sure that the method is safe of self-assigment when we have a class that use dynamic memory.
So, imagine that we have a class named "Bank_Client" with a std::string
in created with new
. The book teach us to do this to avoid the self-assigment case:
Bank_Client& Bank_Client::operator=(const Bank_Client &addres){
std::string *temp = new std::string(*addres.name);
delete name;
name = temp;
return *this;
}
So if i do
Bank_Client bob("Bobinsky");
bob = bob;
The program will not just blow-up. But right when i thought that temp
variable was a waste of time the writer of the book show us another way to do it:
Bank_Client& Bank_Client::operator=(const Bank_Client &addres){
if (this != &addres){
delete name;
name = new std::string(*addres.name);
}
return *this;
}
Like if he read my mind. BUT right after that he tell us to never do that, that is better to do it by the other way but never explain why.
Why is the first way better? It is slower, isn't it? What is the best why to do it?
what about use assert
to check there is no self-assignment? (because we dont really need it). And then desactivate it with the corresponding NDEBUG
then there is no waste of time in the checking.