gpt4 book ai didi

c++ - 这个破坏者是谁的?

转载 作者:太空狗 更新时间:2023-10-29 21:42:19 25 4
gpt4 key购买 nike

在下面的代码中:

#include <string>
#include <iostream>

struct S {
std::string a;
int b;

S(const S&) = default;
S(S&&) = default;
S& operator=(const S&) = default;
S& operator=(S&&) = default; // not required here but should be added for completeness

~S() {
std::cout << a << " " << b << std::endl;
}
};

S f(S arg) {
S s0{};
S s1(s0); //s1 {s0}; in the book
s1 = arg;
return s1;
}

int main()
{
S s3{"tool",42};
f(s3);
}

我得到以下输出(我用我的推理评论了输出):

 42 //???
0 // s0 is destroyed
tool 42 // arg is destroyed
tool 42 // return value of f() is destroyed
tool 42 // s3 is destroyed

输出 42 的析构函数是谁的??看不懂

最佳答案

自动变量以声明的相反顺序被销毁,所以指示的析构函数是s1的析构函数。

它在程序中的那一点取值 {"", 42} 的原因是 f 的返回值正在通过 move 构造进行初始化;也就是说,s1 被视为一个 xvalue。这遵循 [class.copy]/32 中的规则:

When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.

关于c++ - 这个破坏者是谁的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26733576/

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