dimanche 9 avril 2023

Why does variable value not change giving std::move as function argument? [duplicate]

I have looked at other posts regarding std::move but those examples were a bit complicated for me to understand so I will try to explain my problem with a very simple example here.

void increaseNum(int num) {
    num += 1;
}

int main() {
    int myNum {5};
    increaseNum(myNum); // Case-1
    increaseNum(std::move(myNum)) // Case-2
}

In Case-1 it does not change the value of myNum because I am passing it by value. It creates a copy of myNum inside increaseNum and changes the value of copy there. However, in Case-2 what I would expect is that I am saying to increaseNum "Hey, do not create a copy of myNum, instead take the ownership of that variable and change it, like pass by reference". When I print out myNum after Case-2, it is still 5 which confuses me.

Could someone please help me what I am missing here? Is giving std::move(variable) as function argument not the same as pass by reference? If not then why do we give std::move(variable) as function argument?

Aucun commentaire:

Enregistrer un commentaire