我很确定,函数参数的析构函数应该在相应函数的导出处调用。考虑 C++11 标准的 5.2.2p4:
[...] The lifetime of a parameter ends when the function in which it is defined returns. [...]
不过,让我们试试这段代码:
#include <iostream>
using namespace std;
struct Logger {
Logger(int) { cout << "Construct " << this << '\n'; }
Logger(const Logger&) { cout << "Copy construct " << this << '\n'; }
~Logger() { cout << "Destruct " << this << '\n'; }
};
int f(Logger)
{
cout << "Inside f\n";
return 0;
}
int main()
{
f(f(f(10)));
}
用gcc或clang编译后输出如下:
Construct 0x7fffa42d97ff
Inside f
Construct 0x7fffa42d97fe
Inside f
Construct 0x7fffa42d97fd
Inside f
Destruct 0x7fffa42d97fd
Destruct 0x7fffa42d97fe
Destruct 0x7fffa42d97ff
正如我们所见,所有三个参数仅在最后一次函数调用完成后才被销毁。这是正确的行为吗?
最佳答案
参见 C++11 标准,§12.2/3,说
Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.
关于c++ - 函数参数不会在该函数退出时销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27195825/