I have a question regarding the assignment operator (apologies if this has already been answered in a different post).
As I understand the assignment operator, it is suppose to assign the value of one object to another, e.g.
class A {
public:
A();
A& operator=(const A& rhs)
{
b = rhs.b;
return *this;
}
private:
B b;
};
Now, if the class contains pointers, it seems to be common practice to allocate new memory in the assignment operator. This makes the assignment operator more complicated since one needs to be more careful, e.g.
class A {
public:
A() : b(0)
{
b = new B;
}
A& operator=(const A& rhs)
{
if (this != &rhs) {
B* b1 = 0;
try {
b1 = new B(*rhs.b);
}
catch {
delete b1;
throw;
}
delete b;
b = b1;
}
return *this;
}
private:
B* b;
};
So my question is: Why not assign the value of the existing object pointed to, i.e. reuse the memory by calling B's assignment operator as one would do if b was not a pointer (see my first example)? Then the assignment would look like this
class A {
public:
A() : b(0)
{
b = new B;
}
A& operator=(const A& rhs)
{
*b = *rhs.b;
return *this;
}
private:
B* b;
};
This is much more simple and does exactly what I would expect from the assignment operator.
Moreover, I can think of at least one example where the more complicated assignment operator will get me into trouble: If class A has a member function which returns b
const B* A::GetB() const
{
return b;
}
then the following code will leave a dangling pointer
A a1, a2;
const B* my_b = a1.GetB();
a1 = a2; // this leaves my_b dangling!
Your comments are much appreciated. Thanks!