c++ - 本地对象可以完全存在于 C++ 中的硬件寄存器中吗?

标签 c++

在 C++ 中,编译器是否可以优化代码,使本地对象实例完全存在于寄存器中,而不是分配在堆栈中?

例如,使用这段代码:

#include <inttypes.h>

class int24_t {
    int32_t val;
public:
    int24_t(int32_t v = 0) { val = v & 0xffffff; }
    int24_t add(int24_t v) { return int24_t(val + v.val); }
};

int24_t add_two_int24(int24_t a, int24_t b)
{
    return a.add(b);
}

没有虚函数,也没有任何其他额外数据,使得“val”实际上是该对象存储在内存中的唯一数据,因此编译器是否有可能生成如下汇编:

push ebp
mov  ebp, esp
mov  eax, [ebp+8]
add  eax, [ebp+12]
and  eax, 0x00ffffff
pop  ebp
ret

而不是在栈中为对象分配空间?

编辑:

这是可能的。例如,我的计算机 (x64_64) 中的 gcc -march=native -O2 -c 生成此代码:

Disassembly of section .text:

0000000000000000 <add_two_int24(int24_t, int24_t)>:
   0:   8d 04 37                lea    (%rdi,%rsi,1),%eax
   3:   25 ff ff ff 00          and    $0xffffff,%eax
   8:   c3                      retq

最佳答案

是的,如果对象大小小于或等于处理器寄存器的大小,则对象可以存在于处理器的寄存器中。

编译器是否选择这样做是另一回事。生成汇编语言列表。此外,根据需要调整优化级别。

关于c++ - 本地对象可以完全存在于 C++ 中的硬件寄存器中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33108252/

相关文章:

c++ - Linux 上的 AIO 支持

c++ - 专门化模板别名的最佳方法(或解决方法)

c++ - visual c++ 的 pthreads-w32 中的 new 和 delete 运算符是线程安全的吗?

c++ - 使用套接字 rfcomm 的蓝牙连接

c++ - 如何在 Windows 窗体/C++ 中将文本或数字旋转 90°?

c++ - luabind 什么时候释放创建的对象?

c++ - 需要类语法解释

c++ - 当调用改变它的成员函数时,c对象成员没有被改变

c++ - 当非限定名称查找涉及 using-directives 时 [basic.scope.hiding]p2 的解释

android - c++ android ndk 使用数组