I was looking at an explanation of the Rule of Three, and found the following code:
// 1. copy constructor
person(const person& that)
{
name = new char[strlen(that.name) + 1];
strcpy(name, that.name);
age = that.age;
}
// 2. copy assignment operator
person& operator=(const person& that)
{
if (this != &that)
{
delete[] name;
// This is a dangerous point in the flow of execution!
// We have temporarily invalidated the class invariants,
// and the next statement might throw an exception,
// leaving the object in an invalid state :(
name = new char[strlen(that.name) + 1];
strcpy(name, that.name);
age = that.age;
}
return *this;
}
explaining things (found here: What is The Rule of Three?) I wasn't sure if I should ask the question there (since it's been a while since it was posted) or to make a new question, so I hope I don't get in trouble. I just want to see if I understood this code correctly?
From what I'm understanding here is that instead of copying the pointers (and thus having two objects point to the same memory), the object being copied to is dynamically allocating new memory which will then contain the same data that the object that was copy contains? And what is the reason that the copy assignment operator function has "delete [] name]" at the beginning? Is it because when = is used, the pointer is automatically copied and thus this new object points to the same memory as the object copied, and delete [] name deletes that memory before dynamically allocating new memory for it to point to? Actually, I'm not really sure what I'm saying so can somebody explain to me why it uses delete? And finally, what is the purpose of the if (this != &that) part?
Thanks!