【问题标题】:Why is the output 2020?为什么是2020年的输出?
【发布时间】:2021-07-13 05:15:52
【问题描述】:

我有以下代码:

#include <iostream>
using namespace std;

class Foo {
   int data;
public:
   Foo(int d = 0) {
      data = d;
   }

   ~Foo() {
      cout << data;
   }
};

int main() {
   Foo a;
   a = 20;
   return 0;
}

这段代码的输出是 2020。我想会发生什么,创建了一个临时对象 a。一旦使用赋值运算符为 20 赋值,就会调用析构函数并打印 20。然后 main 函数到达 return 并再次调用析构函数,再次打印 20。

我说的对吗?

【问题讨论】:

  • 您的理解似乎是正确的。
  • 准确!你已经明白了。
  • 您的帖子也是一个说明,如果您要覆盖复制构造函数(您没有这样做,只是为了说明这一点),以实现编译器本身将调用复制构造函数你甚至不知道它被调用了。太多的新程序员认为他们在复制构造函数中写的任何东西都是孤立的,只有在他们想要调用复制构造函数时才会被调用,因此编写了复制构造函数中发生的各种疯狂的事情。
  • 提示:你没有operator= 那么a = 20; 中的= 有什么作用?
  • 解锁成就:“C++ 学徒”。

标签: c++ constructor destructor


【解决方案1】:

你是对的。 其实修改你的代码如下,可以更清楚的展示代码的逻辑。

#include <iostream>
using namespace std;

class Foo {
   int data;
public:
   Foo(int d = 0) {
      cout << "call constructor!" << endl;
      data = d;
   }

   ~Foo() {
      cout << data << endl;
   }
};

int main() {
   Foo a; // Foo::Foo(int d = 0) is called which yields the first line of output
   a = 20; // is equal to follows
   
   // 1. a temporary object is constructed which yields the second line of output
   Foo tmp(20);
   // 2. since you do not provide operator= member function,
   // the default one is generated the compiler
   // and a member-wise copy is performed
   a.operator=(&tmp);  
   // after this copy assignment, a.data == 20
   // 3. tmp is destroyed which yields the third line of output
   tmp.~Foo();
   // 4. right before the program exits, a is destroyed which yields the last line of output
   a.~Foo();

   return 0;
}

输出是:

调用构造函数!

调用构造函数!

20

20

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 2018-10-11
    • 2020-05-21
    • 2020-10-13
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多