Why is destructor for a form called twice?

喜夏-厌秋 提交于 2019-12-31 02:13:08

问题


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);
}

I have changed it to

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?


回答1:


   MyApp::MyForm form;

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().

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.

More about stack semantics in this MSDN article.



来源:https://stackoverflow.com/questions/28686486/why-is-destructor-for-a-form-called-twice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!