这是谁的析构函数
Whose destructor is this one?
在下面的代码中:
#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:中的规则
当满足或将满足省略复制操作的条件时,除了源对象是一个函数参数,要复制的对象由左值指定,重载解析为为第一次执行的复制选择构造函数,就好像对象是由右值指定的一样。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- C++:使用方法调用析构函数的顺序是什么?
- 创建析构函数是好的编程实践吗?
- 当我使用dynamic_cast并删除对象删除时,析构函数是如何工作的?
- 重写析构函数是好的做法吗?
- 析构函数是移动ctor/赋值的RHS上唯一调用过的东西吗
- 静态对象的私有析构函数是如何调用的
- 基类析构函数不是虚拟的,子类析构函数是虚拟的,程序崩溃
- 如果基类析构函数是虚拟的,是否需要派生类析构函数定义
- 这是谁的析构函数
- 这个C++析构函数是多余的吗
- 使用常量析构函数是很有用的
- 正在转换到C++11,其中析构函数是用noexcept隐式声明的
- 当类的指针实例超出范围时不调用析构函数是真的吗?
- c++中的虚析构函数是如何工作的
- 在以下情况下手动调用析构函数是一个糟糕的设计决策吗?
- 抽象类的虚析构函数是模糊的
- C++析构函数是如何调用的
- 当派生类的析构函数是虚拟的而基类的 dtor 不是时,代码崩溃
- 如果一个类继承自纯基类,那么默认析构函数是什么?