在WndProc消息(WM_CREATE)中声明和初始化的智能指针对象的寿命

如果我像这样在主窗口回调函数中声明和初始化对象:

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.

谢谢你的帮助!

评论
也,許
也,許
WM_CREATE消息中断后,对象foo是否会保持初始化状态?

No. foo gets destroyed when it goes out of scope at the } before the break.

声明它的最佳位置在哪里,以便它的范围不受大小写范围的限制?

您可以在函数范围内声明它,然后从函数返回时它将被销毁。

{
    std::unique_ptr<Foo> foo;
    switch (msg)
    {
        case WM_CREATE:
        {
            foo = std::make_unique<Foo>();
        }
        break;
    }
} // foo gets destroyed here

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.

点赞
评论