析构函数不在控制台上打印行

Destructor doesn't print line on console

我正在使用 visual studio 2013 并打印一些 cout 命令进行测试,当我调试我的代码时,控件进入两个 class 的析构函数,但它没有在控制台上打印 cout 语句.

#include <iostream>  
using namespace std;

class Uni
{
 public:
 ~Uni()
 {
    cout << "I am in Uni Destructor" << endl;
 }

 Uni()
 {
    cout << "I am in Uni Constructor" << endl;
 }

};


class Student: public Uni
{
 public:

 Student()
 {
    cout << "I am in Student Constructor" << endl;
 }
 ~Student()
 {
    cout << "I am in Student Destructor" << endl;
 }



};

int main()
{
  Student s;
  system("pause");
  return 0;
}

输出:

我在Uni Constructor

我在 Student Constructor

我想你此时得到了输出,即在 pause.

之后
int main()
{
  Student s;
  system("pause");

  // here; but s is not destroyed yet
  return 0;
}

但那时 s 还没有被摧毁。当离开它声明的范围时,它将被销毁,即当离开函数 main.

您可以将 s 放入进一步的范围进行测试。

int main()
{
  {
    Student s;
  } // s will be destroyed here

  system("pause");
  return 0;
}

您的代码看起来不错,cout 是一个缓冲的控制台输出流对象实例:您确定您的析构函数消息不只是缓冲以在 cout 的最后一个右大括号和刷新之后写入吗?