问题
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