析构函数不起作用?

Suh*_*pta 2 c++ visual-c++

#include <iostream>

using namespace std;

class Tester {
public:
Tester(int x);
~Tester();
int who;
} Tester_g_1(1) , Tester_g_2(2);

Tester::Tester(int id) {
cout << "Intializing" << id << endl ;
who = id;
}

Tester::~Tester() {
cout << "Destroying" << who << endl;
}

int main() {
Tester localObj(3);
cout << "This is not the first line to be displayed";
    system("pause");
return 0;

}
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

Intializing1
Intializing2
Intializing3
This is not the first line to be displayedPress any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

为什么析构函数dodes中的语句不起作用? 使用中: 编译器 - microsoft visual c ++ 2010 Express OS - Win7

Mat*_*lia 10

localObj当被破坏main终止(因为它的它的范围),这恰好经过system("pause").你按一个键,析构函数会运行,但窗口会立即关闭,所以你看不到它.

要查看析构函数的文本,您必须从命令行运行程序,或使用"运行"菜单中的"启动程序而不调试"项目(IIRC VS菜单)(热键为Ctrl+ F5- 谢谢@Cody灰色).在可执行文件终止后,这会添加"按任意键继续",这样您就可以看到析构函数写入的文本.

查看析构函数运行的另一种方法是将变量封装在较小的范围内,您可以这样轻松地执行此操作:

// ...

int main() {
    {    // the braces create a new scope...
        Tester localObj(3);
        cout<<"Inside the Tester scope..."<<endl;
    }    // ... that ends here
    cout << "... outside the Tester scope!";
    cout<<"Press Enter to exit...";
    cin.ignore();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,system("pause")是丑陋和不便携的; 你应该避免它.

  • 例如`cin.ignore()`.但根据我的经验,在计划结束时暂停并不是真的需要.如果你在调试器中运行它,你可以简单地在`main`的`return`上添加一个断点,如果你从VS运行它并且你没有使用调试器你可以只做Ctrl + F5,如果你是从控制台运行它你不需要它,因为窗口没有关闭. (2认同)