如果我像这样在主窗口回调函数中声明和初始化对象:
LRESULT CALLBACK WndProc
(
HWND hWnd // handle to window of this process
, UINT msg // message constant
, WPARAM wParam // holder of message parameters
, LPARAM lParam // holder of message parameters
)
{
switch (msg)
{
case WM_CREATE:
{
std::unique_ptr<Foo> foo = std::unique_ptr<Foo>(new Foo);
}
break;
}
}
Will the object foo
stay initialized after the break
of WM_CREATE
message? And if not, where is the best place to declare it so that it's scope is not limited by the case
scope?
The foo
object is creating controls in the main window by the way so I think the requirement is to let it live till the end of runtime.
I suspect it will not survive. I am thinking about declaring those as global variable (but I don't like that option for obvious reasons) or as static objects within the callback function (but outside the switch
). But there might be better options I don't see, so I am seeking your advice.
谢谢你的帮助!
No.
foo
gets destroyed when it goes out of scope at the}
before the break.您可以在函数范围内声明它,然后从函数返回时它将被销毁。
If you need it to live on even after the function returns you need to declare it outside the function. You can possibly pass it as an
LPARAM
to the callback function.