gpt4 book ai didi

c++ - 返回值两份

转载 作者:行者123 更新时间:2023-11-30 01:44:26 25 4
gpt4 key购买 nike

我正在按函数分析返回值。请参阅下面的实际问题:

struct S{ int a, b, c, d;  };
S f(){
S s;
s.b=5;
return s;
}

int main(){
S s= f();
s.a =2;
}

来自 gcc 5.3 -O0 -fno-elide-constructors on godbolt 的编译器输出:

f():
pushq %rbp
movq %rsp, %rbp
subq $32, %rsp
movl $5, -28(%rbp)
leaq -32(%rbp), %rdx
leaq -16(%rbp), %rax
movq %rdx, %rsi
movq %rax, %rdi
call S::S(S const&)
movq -16(%rbp), %rax
movq -8(%rbp), %rdx
leave
ret
main:
pushq %rbp
movq %rsp, %rbp
subq $32, %rsp
call f()
movq %rax, -16(%rbp)
movq %rdx, -8(%rbp)
leaq -16(%rbp), %rdx
leaq -32(%rbp), %rax
movq %rdx, %rsi
movq %rax, %rdi
call S::S(S const&)
movl $2, -32(%rbp)
movl $0, %eax
leave
ret

我的问题是什么?

  1. 为什么有两个拷贝构造函数?我不明白为什么需要它。

最佳答案

f() 中的复制构造函数被调用,因为使用了对象的“返回”。这会提示它创建一个拷贝到一个临时变量中,然后将其传递给 main。 main 中的复制构造函数很明显 f() 返回一个 S 对象,它被复制到“s

关于c++ - 返回值两份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36205215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com