0

I feel pass by reference and a move has a same result. In the below example both move semantic and pass by reference has same outcome. I was assuming when we use move semantics the ownership is passed on the the function and in main the variable does not hold any value.

#include <iostream>

using namespace std;
void move_function(int&& a)
{
    cout<<"a:"<<a<<endl;
    a++;
    cout<<"a:"<<a<<endl;
}

void function(int& val)
{
    val++;
    cout<<"val:"<<val<<endl;;
}

int main()
{
    int a = 100;
    move_function(move(a));
    cout<<"main a:"<<a<<endl;
    function(a);
    cout<<"main a:"<<a<<endl;

    return 0;
}

can someone give me some light on my confusion. Where has my understanding about move gone wrong?

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
arjun jawalkar
  • 138
  • 1
  • 10

2 Answers2

2

Move() gives ownership to your new object. It is useful in multi-threading where you want to pass the ownership of a mutex to a lock.

Pass by reference is a way of passing objects between functions by creating an alias.

Telenoobies
  • 938
  • 3
  • 16
  • 33
0

Reference create an alias of the varialbe that is passed. Move is something different. Move "steals" the value that a variable holds. For example if you have

  void foo(void)
  {
     std::shared_ptr<int> p = std::make_shared<int>();
    std::shared_ptr<int> ps = std::move(p);//after execution p has expired
    std::cout << "count:" << ps.use_count() << std::endl;
    std::cout << "count:" << p.use_count() << std::endl;
    std::shared_ptr<int> ps2 = ps;// simple copy,after executuion the reference count 
                                 // is 2 
    std::cout << "count:" << ps2.use_count() << std::endl;
  }

When this routine will be executed the ps shared pointer will steal the value of the p and p will be espired. But when the ps2 is defined , the content of the ps will be copied to this and reference count will be increased . The new value will be 2.

getsoubl
  • 808
  • 10
  • 25
  • 1
    `std::move` doesn't steal anything. It doesn't even move. It just gives you an rvalue. It is conventional move ctors/assignment ops that may steal stuff. – Lightness Races in Orbit May 08 '19 at 14:22
  • 4
    @LightnessRacesinOrbit One can think of it as giving "permission to steal". The recipient is not required to steal, but they have permission to do so. (As you noted, it formally converts the object to an rvalue, but the main thing about rvalues in this context is that they are temporary and therefore stealable.) – Raymond Chen May 08 '19 at 14:25
  • 1
    @RaymondChen That's right. – Lightness Races in Orbit May 08 '19 at 14:34
  • @RaymondChen extactly that you described in details , I meant with the phrase "steal" – getsoubl May 09 '19 at 07:36