c++ - 函数参数不会在该函数退出时销毁

标签 c++

我很确定,函数参数的析构函数应该在相应函数的导出处调用。考虑 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/

相关文章:

c++ - 从插槽Blackberry 10中获取TextField-> text()

c++ - 使用 class::factory(); 实现 operator<<

c++ - g++ 模板类中的 undefined reference

C++函数参数: use a reference or a pointer (and then dereference)?

c++ - 这种用于创建异构仿函数容器的技术能否得到挽救?

c++ - 在 C 或 C++ 中从 LaTeX 制作 PNG|jpeg

c++ - 无法获取字符串以从文本文件中打印随机行

c++ - unique_ptr 中原始指针的默认删除器

c++ - 如何从模板类的可变包中的每个类型中恢复非类型名模板参数?

c++ - 是什么导致 move 赋值运算符不被调用?