在下面的代码中:
#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
被处理为x值。这遵循[class.copy]/32:中的规则
当满足或将满足省略复制操作的条件时,除了源对象是一个函数参数,要复制的对象由左值指定,重载解析为为第一次执行的复制选择构造函数,就好像对象是由右值指定的一样。