Need for move constructor and also operator=?

Hi guys I am reading this tutorial https://stackoverflow.com/questions/3106110/what-are-move-semantics

he says when we use the copy assignment in this example the object in the arguments has to be initialised this is done by the compiler,the compiler chooses weather to use the move constructor or copy constructor depending on weather the object passed is a lvalue or rvalue,

all makes sense

but for example lets say that we pass an rvalue object into the assignment operator function,the object will be initialised using the move constructor basically stealing the rvalues data,when this is done we have our new object but now our operator assignment function is not over it still has to run so we call std::swap() and swap the objects so we are swapping the rvalue with our current value,so isn't this step a bit redundant? since we have already created the object with the rvalues data,why the nee to copy again when we pretty much have the object we wanted?

thanks
hi TheIdeasMan

yes its the copy and swap idiom but the copy and swap idiom on stackoverflow didn't answer my question or maybe it did and I missed it?

thanks
Hi,


adam2016 wrote:
..... when this is done we have our new object but now our operator assignment function is not over it still has to run so we call std::swap() and swap the objects so we are swapping the rvalue with our current value,so isn't this step a bit redundant?


This part answers it I think: in the move semantics answer (your link in the OP), just after the operator= code:
SO_move_semantics wrote:

In the olden days of C++98, the answer would have been "by the copy constructor". In C++0x, the compiler chooses between the copy constructor and the move constructor based on whether the argument to the assignment operator is an lvalue or an rvalue.


Emphasis added by me :+)

So the move ctor doesn't call operator=
Last edited on
thanks theIdeasMan :)
sorry again just a follow up I re read both articles a few times and tried practicing and going through the code myself,

so from what I understand as explained if we use an lvalue the assignment operator will construct an object with the copy constructor if an rvalue it will construct an object with the move constructor,so lets say we choose the latter

lets say we have a function that swaps objects members and below is the assignment operator,so as I said lets say we have an rvalue first the operator= will construct an object with the move constructor so why so we need the swap function here??

we have already accomplished what we want we have made an object with the move constructor and "stolen or taken" the data we needed so whats the need for the extra swap?

aren't we just doing the same thing all over again just swapping?

thanks

1
2
3
4
5
6
7
dumb_array& operator=(dumb_array other) // (1)
{
    swap(*this, other); // (2)

    return *this;
}
Topic archived. No new replies allowed.