以下代码使用了一个修改i
的析构函数。当析构函数运行时,2
应该存储到 i
中,但是当 thing()
返回时,我们观察到 -1
.
#include <stdio.h>
class Destruct {
int &i;
public:
Destruct(int &_i) : i(_i) {}
~Destruct() {
i = 2;
}
};
int thing() {
int i = -1;
Destruct d(i);
return i;
}
int main() {
printf("i: %d\n", thing());
}
最佳答案
int thing() {
int i = -1;
Destruct d(i);
return i;
}
对象d
在函数返回时被析构,堆栈清理开始!到调用析构函数时,返回值已经复制到返回寄存器。
你想看的,可以这样看:
int thing() {
int i = -1;
{
Destruct d(i); //put it inside braces!
}
return i;
}
来自您的评论:
That is how it works, a disassembly of the code shows that this is the case. I am curious as to why.
逻辑很简单,可以这样证明:假设析构函数在 i
被复制到返回寄存器之前被调用,那么为什么要选择性地销毁 d
和不是 i
也是吗?毕竟两者都是局部变量。所以如果d
被析构,那么i
也应该被析构,之前它的值被复制到返回注册但这没有意义。
正如@Luc Touraille 所问(在评论中):“如果您的函数返回d
怎么办?您确定要销毁d
吗? 在被传递给调用者之前?”
关于c++ - 为什么析构函数不修改返回的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11686410/