Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this C++0x optimization legal?

Tags:

c++

c++11

Is it legal for a C++0x compiler to optimize

int func(int&& a){
    a = 3;
    return a;
}

to

int func(int&& a){
    return 3;
}

? (or for another POD)

like image 529
Emil Avatar asked Aug 22 '11 21:08

Emil


1 Answers

Not like that per se, because the function must modify the variable a to be equivalent. That said, after inlining and a bit of trivial optimization the result will be the same:

int x = func(5);

// pseudo-inlined:
int __temp = 5; // the temporary created by binding 5 to int&&
__temp = 3; // a = 3;
int x = __temp; // return a;

// constant propagation:
int __temp = 5;
__temp = 3;
int x = 3;

// dead-code elimination:
int x = 3;

Note the result is the same as if you used the second definition of func and inlined, only because the temporary variable wasn't used. This shows that the two functions aren't equivalent in general:

int modifyme = 100;
int x = func(std::move(modifyme));

// modifyme must be 3, second function definition wouldn't do that
like image 141
GManNickG Avatar answered Oct 15 '22 02:10

GManNickG