开发者

Is this C++0x optimization legal?

开发者 https://www.devze.com 2023-03-29 18:10 出处:网络
Is it legal for a C++0x compiler to optimize int func(int&& a){ a = 3; return a; } to int func(int&& a){

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 anothe开发者_StackOverflow社区r POD)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消