Do C++11 compilers turn local variables into rvalues when they can during code optimization?(在代码优化期间,C++11 编译器是否会将局部变量转换为右值?)
问题描述
有时将复杂或长的表达式拆分为多个步骤是明智的,例如(第二个版本不是更清楚,但它只是一个示例):
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 编译器是否会将局部变量转换为右值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在代码优化期间,C++11 编译器是否会将局部变量转换为右值?


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01