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 编译器是否会将局部变量转换为右值?
基础教程推荐
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
