1

I am trying to understand the c++11's newly introduced std::move() function. In the following code snippet:

typedef struct
{
    int i, j;
} TwoNumbers;

void foo(TwoNumbers&& a)
{

}

int main ()
{
    TwoNumbers A{0, 1};
    cout << A.i << A.j << endl;
    foo(move(A));
    cout << A.i << A.j << endl;
    return 0;
}

how is the output coming as the following ?

ayan@ayan-Aspire-E1-571:~/Desktop$ g++ main.cpp -o main -std=c++11
ayan@ayan-Aspire-E1-571:~/Desktop$ ./main 
01
01

What I thought:

I thought that the std::move() will convert my object A to an rvalue and transfer the ownership to the function foo() and I will no longer get the object A in its initialised state. But that's not the case here. WHY?

Saurav Sahu
  • 9,755
  • 5
  • 42
  • 64
Ayan Das
  • 473
  • 4
  • 14
  • There is no such thing as "transfer ownership to a function". The parameter of `foo` is a reference , it refers to `A`. You *could* write code in the body of `foo` which modifies `a`, but you didn't, so nothing changed. – M.M Dec 27 '16 at 13:31
  • Also there is no such thing as "convert object to an rvalue". Only expressions may be converted as such. Converting the expression `A` to rvalue has no effect on the object referred to – M.M Dec 27 '16 at 13:32
  • 4
    I need to get acustomed to move myself (btw it made me smile when I read "newly introduced" ;), but my current understanding is: `move` doesnt actually do anything, but just tells your `foo` that it is allowed to "rip the parameter apart" because it wont be used any further. However, as your `foo` does not do anything with its parameter, you get the output you see. – 463035818_is_not_a_number Dec 27 '16 at 13:36

0 Answers0