Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

difference between using std::move and adding 0 to the number?

I’m curious about that is there any practical difference between using std::move to convert an l-value integer to r-value, and adding a 0 to that integer? or any other neutral arithmetic operation (multiplying by 1, subtracting 0, etc).

Adding 0:

int f(int&& i){
    i++;
    return i;
}


int main(){
    int x = 43;
    f(x+0);
}

Using std::move:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <iostream>

int f(int&& i){
    i++;
    return i;
}


int main(){
    int x = 43;
    f(std::move(x));
}

I know we cannot perform such neutral actions on all types, but my question is specially about integral numbers not other types.

>Solution :

std::move(x) and x+0 do not do the same thing.

The former gives you an rvalue (specifically xvalue) referring to x. The latter gives you a rvalue (specifically prvalue) which (after temporary materialization) refers to a temporary object with lifetime ending after the full-expression.

So f(x+0); does not cause x to be modified, while f(std::move(x)) does.

Taking a rvalue-reference to an int specifically is probably pointless. Moving and copying scalar types is exactly the same operation, so there is no benefit over just int&.

And your function both returns the result and tries to modify the argument. It should do only one of those things. If it takes a reference and modifies the argument it should either have void return value or return a reference to the argument. If it ought to return the result by-value, then it doesn’t need to be passed a reference and can just take a int parameter.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading