How does Copy-and-swap work?

0

I've been reviewing C ++ 11 and C ++ 14 news, and I do not understand how Copy-and-swap works

As an example:

class dumb_array
{
public:
// ...

friend void swap(dumb_array& first, dumb_array& second) // nothrow
{
    // enable ADL (not necessary in our case, but good practice)
    using std::swap;

    // by swapping the members of two objects,
    // the two objects are effectively swapped
    swap(first.mSize, second.mSize);
    swap(first.mArray, second.mArray);
}

// ...
};


dumb_array& operator=(dumb_array other) // (1)
{
    swap(*this, other); // (2)
    return *this;
}

(The source of the code is GManNickG , thanks for the reply in this post.)

I do not understand why the object is copied instead of exchanged. When calling swap (a, b), according to the definition of std :: swap , the values should be interchanged operator = returns the object, which now has the attributes of other . But why does other still have its attributes instead of exchanging them?

Sorry if my question sounds stupid, but I'm trying to assimilate all the concepts that modern C ++ has and it's costing me a lot.

    
asked by David Maseda Neira 09.06.2017 в 14:28
source

1 answer

1
dumb_array& operator=(dumb_array other) // (1)
{
    swap(*this, other); // (2)
    return *this;
}

(1) Note that the other parameter is a copy of the call argument.

(2) swap (* this, other); exchange the members of * this with those of other (with this other of (1), which is the copy of the object that was passed to him when invoking this function).

Capisce?

    
answered by 09.06.2017 / 23:04
source