小编wis*_*spi的帖子

函数返回的类的析构函数

我有以下代码:

#include <stdio.h>

class Foo {
    public:
    int a;
    ~Foo() { printf("Goodbye %d\n", a); }
};

Foo newObj() {
    Foo obj;
    return obj;
}

int main() {
    Foo bar = newObj();
    bar.a = 5;
    bar = newObj();
}
Run Code Online (Sandbox Code Playgroud)

当我编译g++并运行它时,我得到:

Goodbye 32765
Goodbye 32765
Run Code Online (Sandbox Code Playgroud)

打印的数字似乎是随机的。

我有两个问题:

  1. 为什么析构函数被调用两次?
  2. 为什么5第一次不打印?

我来自C的背景,因此来自printf,并且在理解析构函数,调用它们的时间以及如何从函数返回类时遇到了麻烦。

c++ destructor g++ class

3
推荐指数
1
解决办法
128
查看次数

标签 统计

c++ ×1

class ×1

destructor ×1

g++ ×1