mercredi 8 mai 2019

What is difference between std::move and pass by reference in C++?

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?

Aucun commentaire:

Enregistrer un commentaire