Im writing a copy assignment operator for a class I've created and I'm using a previous post as a guide: What is The Rule of Three?
Im a bit confused on one aspect of this person's explanation.
Here is their class:
class person
{
char* name;
int age;
};
Here is the copy assignment operator definition that I am using as a reference (there are at least 2 offered):
// 2. copy assignment operator
person& operator=(const person& that)
{
char* local_name = new char[strlen(that.name) + 1];
// If the above statement throws,
// the object is still in the same state as before.
// None of the following statements will throw an exception :)
strcpy(local_name, that.name);
delete[] name;
name = local_name;
age = that.age;
return *this;
}
What I'm finding confusing is, why are they including the line delete[] name;
?
Here is the other example they provide:
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;
}
I immediately shied away from this one because I couldn't understand why the function checks if(this != &that)
and then runs delete (delete[] name;) on an array that doesn't seem to have been generated yet. When the assignment operator is invoked, is the regular constructor called immediately before the copy assignment operator function is called? Therefore meaning that we must delete the array that was generated by the classes constructor because it can only be full of junk data?
Why can't I just write:
name = that.name
or
name = new char[that.name.size()];
for (int i = 0; i < that.name.size(); i++)`
{
name[i] = that.name[i]
}
This is probably really basic and I should just implement what the post suggests but my actual use-case involves an array of struct
s with multiple members and so Im just having a little bit of a difficulty understanding what exactly I need to do.
I realize there are like 2.5 questions here. Any insight would be appreciated.
This is my first time implementing custom copy constructors and copy assignment operators and Im sure it will seem easy after I've done it a few times.
Thanks in advance.