有时将复杂或长的表达式拆分为多个步骤是明智的,例如(第二个版本不是更清楚,但它只是一个示例):
Sometimes it's wise to split complicated or long expressions into multiple steps, for example (the 2nd version isn't more clear, but it's just an example):
return object1(object2(object3(x)));
可以写成:
object3 a(x);
object2 b(a);
object1 c(b);
return c;
假设所有 3 个类都实现了以右值作为参数的构造函数,第一个版本可能会更快,因为临时对象被传递并且可以移动.我假设在第二个版本中,局部变量被认为是左值.但是,如果以后不使用这些变量,C++11 编译器是否会优化代码,以便将变量视为右值并且两个版本的工作方式完全相同?我最感兴趣的是 Visual Studio 2013 的 C++ 编译器,但我也很高兴知道 GCC 编译器在这件事上的表现.
Assuming all 3 classes implement constructors that take rvalue as a parameter, the first version might be faster, because temporary objects are passed and can be moved. I'm assuming that in the 2nd version, the local variables are considered to be lvalues. But if the variables aren't later used, do C++11 compilers optimize the code so the variables are considered to be rvalues and both versions work exactly the same? I'm mostly interested in Visual Studio 2013's C++ compiler, but I'm also happy know how the GCC compiler behaves in this matter.
谢谢,迈克尔
在这种情况下,编译器无法打破as-if"规则.但是你可以使用std::move
来达到想要的效果:
The compiler cannot break the "as-if" rule in this case. But you can use std::move
to achieve the desired effect:
object3 a(x);
object2 b(std::move(a));
object1 c(std::move(b));
return c;
这篇关于在代码优化期间,C++11 编译器是否会将局部变量转换为右值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!