A.P.
A.P.

Reputation: 481

Why do we have to empty the current vector when overloading the assignment operator? C++

May someone please explain why does the current vector has to be emptied in the example below (in the while loop)? What happens if the current vector is already empty? May you also give a simple example of how you would use the overloaded operator? This is under a coplien form.

Thanks for clearing those things up.

Type& Type::operator =(const Type& p_vector2)
    {
        if (this != &p_vector2)
        {

            int i = 0;
            int j = vector1.size();
            while (i < j)
            {
                delete vector1[0];
                this->vector1.erase(vector1.begin());
                i++;
            }

            for (unsigned int i=0; i < p_vector2.vector1.size(); i++)
            {
                this->vector1.push_back(vector2.vector1[i][0].clone());
            }
        }

        return *this;
    }

Upvotes: 0

Views: 86

Answers (1)

Ed Swangren
Ed Swangren

Reputation: 124642

May someone please explain why does the current vector has to be emptied in the example below (in the while loop)?

Because the author, for whatever reason, decided to store pointers to dynamically allocated memory. It is now his (your) responsibility to deallocate those objects as the vector cannot do it. This is probably a bad idea, but who knows, perhaps there is a good reason for it.

I can't explain why he doesn't just deallocate and then call clear after the loop.

What happens if the current vector is already empty?

Then the loop would never execute because i and j would be 0, and 0 is not less than 0.

May you also give a simple example of how you would use the overloaded operator?

Type t1;
Type t2;
t2 = t1;

Upvotes: 3

Related Questions