一款 C++0x 编译器能否进行优化是合法的吗?
int func(int&& a){
a = 3;
return a;
}
为了
int func(int&& a){
return 3;
}
(或者对于另一个 POD)
。并不是如此,因为该函数必须修改变量a
以使其等效。话虽如此,在展开后进行一些微不足道的优化后,结果将是相同的:
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;
func
定义并内联的结果是一样的,只是因为临时变量没有被使用。这表明这两个函数在一般情况下是不等价的。int modifyme = 100;
int x = func(std::move(modifyme));
// modifyme must be 3, second function definition wouldn't do that
std::move(modifyme)
只是static_cast<int&&>(modifyme)
的简写,我没有看到标准中有任何暗示从中读取会导致未定义行为的内容,尽管在这方面我了解得不够深入。它只是改变了值类别,仍然是一个常规变量,在我的理解中。 - GManNickGa
赋值为3(return a=3
)。然而,可能情况是该赋值语句也被优化掉了。 - Mooing Duck