为什么一个表单的析构函数叫两次? [英] Why is destructor for a form called twice?

查看:142
本文介绍了为什么一个表单的析构函数叫两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码与入口点调用表单的析构函数两次。

This code with entry point calls form's destructor twice.

void Main(array<String^>^ args)
{
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);
    MyApp::MyForm form;
    Application::Run(%form);
}

我已将其更改为

void Main(array<String^>^ args)
{
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);
    Application::Run(gcnew MyApp::MyForm);
}

第二个版本只调用析构函数一次。

The second version calls destructor one time only.

为什么最初叫它两次?

Why initially was it called twice?

推荐答案

   MyApp::MyForm form;

这是非常错误的。知道什么时候在变量声明上使用^ hat是超级重复的在C ++ / CLI重要。当你不使用它,就像你在这里,然后你调用堆栈语义。它是C ++ RAII模式的一个模拟,编译器自动发出一个调用到Main()结束的析构函数。

That's quite wrong. Knowing when to use the ^ hat on a variable declaration is super-duper important in C++/CLI. When you don't use it, like you did here, then you invoke "stack semantics". It is an emulation of the C++ RAII pattern, the compiler automatically emits a call to the destructor at the end of Main().

但这不应该发生,析构函数的MyForm对象将在您关闭窗口时自动调用。所以在你的情况下,你看到它运行两次。实际上并不是致命的,非常不同于原生C ++,除非你在析构函数中使用本地代码做一些不平凡的事情。请记住,ref类型的析构函数与对象销毁没有任何关系,这是垃圾收集器的工作。

But that should not happen, the destructor of the MyForm object is automatically called when you close the window. So in your case you see it running twice. Not actually fatal, very unlike native C++, unless you do something non-trivial with native code in the destructor. Keep in mind that the destructor of a ref type doesn't have anything to do with object destruction, that's the job of the garbage collector. It is only meant for cleanup of native resources.

有关堆栈语义的更多信息,请参阅此MSDN文章

More about stack semantics in this MSDN article.

这篇关于为什么一个表单的析构函数叫两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆