C++20:用寄存器返回基础类型是否涉及临时物化及标准依据?
在C++20工作草案N4868中,[stmt.return]/2对return语句的行为做了明确规定:
the return statement initializes the glvalue result or prvalue result object of the (explicit or implicit) function call by copy-initialization (9.4) from the operand.
类类型的处理逻辑
对于类类型,return语句会通过选定的构造函数,以复制初始化的方式创建函数调用的结果对象,这一过程可通过**复制消除(copy-elision)**优化实现——调用者直接传递目标对象的地址,被调用函数直接在该地址上初始化对象,无需额外复制操作。示例代码如下:
class MyClass { int x; }; MyClass func() { return MyClass(); // 直接初始化函数调用的结果对象 } int main() { MyClass obj {func()}; // obj即为func()调用的结果对象 }
对应的标准条款[dcl.init.general]/16.6.1补充说明:
If the initializer expression is a prvalue and the cv-unqualified version of the source type is the same class as the class of the destination, the initializer expression is used to initialize the destination object
基础类型的常见实现
对于int、double等基础类型,编译器通常采用寄存器返回的实现方式。以gcc 12.1(编译选项-std=c++20)编译以下代码为例:
int func() { return 2; } int main() { int myInt {func()}; }
生成的汇编代码为:
func(): push rbp mov rbp, rsp mov eax, 2 pop rbp ret main: push rbp mov rbp, rsp sub rsp, 16 call func() mov DWORD PTR [rbp-4], eax mov eax, 0 leave ret
临时对象相关标准条款
[class.temporary]/1.2规定,对于平凡可复制(trivially copyable)类型,实现可根据需要物化临时对象:
1 Temporary objects are created
[...]
—(1.2) when needed by the implementation to pass or return an object of trivially copyable type (see below),
[...]
技术问询
- 针对基础类型的寄存器返回实现,是否以[class.temporary]/1.2作为标准依据?
- 如果是,函数调用是否会通过寄存器物化临时对象,且return语句通过复制初始化的方式初始化该临时对象?
内容的提问来源于stack exchange,提问作者Manuel

