Stav Lobel
Stav Lobel

Reputation: 13

Assignment Operator Overloading and Self Assignment

I've tried to understand Why in '=' overloading I have to check for self Assignment .I think i know the answer , it's because endless loop but I can't understand why the loop is started ?.

Example :

Point p1(3,5);
p1 = p1 ;

Upvotes: 1

Views: 84

Answers (2)

Quentin
Quentin

Reputation: 63124

It's not about endless recursion, at least not usually. The frequent issue with self-assignment is when you try to destroy a resource you own before copying the other object's one: if this object is actually the same, the resource is lost.

struct Object {
    std::unique_ptr<Resource> _resource;

    Object &operator = (Object const &other) {
        _resource = nullptr;                // Destroy "my" resource
        _resource = clone(other._resource); // Nothing to clone anymore...
    }
};

The example is contrived: no one would first reset a pointer, then assign it. But this pattern popped up a lot in older C++, and is the origin of the "beware of self-assignment" advice.

Upvotes: 4

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

There is no loop. What can happen is when you have a resource like some allocated memory.

If you have a shared pointer on some data. During the assignment, the first thing you do is de allocate your local data. Then you replace it with the data from the other object. If they are the same, then you lost your resource.

The solution is then to check self assignments.

Upvotes: 1

Related Questions