Reputation: 3287
I saw the following code somewhere:
class Person {
private:
string *customerName;
public:
Person() {customerName = new string;}
void setCustomerName(char *s) {*customerName = s;}
};
int main()
{
Person person1;
Person person2;
person1.setCustomerName("Malcolm");
person2 = person1;
}
are person1 and person2 all point to the same memory? and if person1 is deleted, or person2 is deleted, what will happen? does it will cause the corrupt the other object? or a memory leak?
Upvotes: 0
Views: 83
Reputation: 727047
person1
andperson2
all point to the same memory?
Their customerName
pointers do point to the same memory, but the objects themselves are separate (albeit thay have an identical content).
and if
person1
is deleted, orperson2
is deleted, what will happen?
Neither one can be deleted, but they can go out of scope. Nothing would happen, because there is no destructor (which is bad).
does it will cause the corrupt the other object? or a memory leak?
An object of type Person
going out of scope or being deleted would cause a memory leak even without an assignment. That is the fault of the Person
class, because it does not have a destructor.
Every time you have an allocation in the constructor, you need a destructor to re-allocate the resources the constructor allocates. Once you add a destructor, The Rule of Three becomes relevant: you need to implement all of the following:
With all three functions implemented, your Person
class becomes safe and leak-free: assignment of person1
to person2
cleans up the current customerName
before making an assignment, and copies the string. Now two objects point to separate customerName
s, ensuring that these could be destroyed without bringing each other down.
Note: Every time you see an explicit allocation in the constructor, ask yourself if that allocation is absolutely necessary, and that the pointer cannot be replaced with an object.
In case of your Person
class the answer to "is the pointer necessary?" question is a resounding "no": you can easily make string *customerName;
a string customerName;
, which would immediately free you from the need to add a destructor, a copy constructor, or an assignment operator. Everything would "just work" - without memory leaks, double-deletes, or any other undesirable side effects.
Upvotes: 4