handling pointer field during object assignment

class inner {int innerVal;};
class outer{
    int val;
    inner * inptr;
How do you overload the assignment op?

outer.val is simply bitwise copy. My solution (Sol1) for inptr is

  *inptr = *(rhs.inptr);

Q: what if the *inptr memory cells are already returned to freelist? i.e. intptr pointee is on heap and deallocated.

The suggested solution (Sol20 is

delete inptr;
inptr = new inner();
*inptr = *(rhs.inptr);

Let’s compare Sol1 and Sol2
– If we have control in place to prevent accidental deletion of the inptr pointee, then Sol1 is faster.
– If our control is weaker and only guarantees that after deletion, the 32-bit object inptr always gets ==reseated== to NULL, then Sol1 is not safe as Sol2
– Without control, then when we want to access or delete inptr, we will worry it could be pointing to freelist, or a valid object. We dare not delete or read/write; and we don’t want it to leak either. No good solution. I would risk double-delete because memory leak is worse. Leak is harder to detect.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s