gpt4 book ai didi

c++ - 将值插入可能为空指针的更简单方法

转载 作者:行者123 更新时间:2023-12-01 22:03:45 27 4
gpt4 key购买 nike

我有一个指针,我希望指向我从函数返回的LRESULT。目前,为了插入从函数返回的值,我将其存储在临时变量中,然后使指针指向该变量。我想知道是否有一种方法可以在不使用临时变量的情况下执行此操作。

编码示例如下:

LRESULT* ret = nullptr;
//---
LRESULT temp = foo();
ret = &temp;
//---
return ret == nullptr ? bar() : *ret;

我尝试过使用这个:

*ret = foo();

但这不起作用,因为 ret 是一个空指针,并且没有分配内存来存放该值。

我也尝试过这个:

ret = &(foo());

但这并不奏效。

编辑:

对于上下文,我正在开发的完整功能如下:

LRESULT CALLBACK Window::HandleMsgSetup(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)  noexcept
{
LRESULT* ret = nullptr;
if (msg == WM_NCCREATE)
{
const CREATESTRUCTW* const pCreate = reinterpret_cast<CREATESTRUCTW*>(lParam);
Window* const pWnd = static_cast<Window*>(pCreate->lpCreateParams);
SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pWnd));
SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(&Window::HandleMsgThunk));
LRESULT lr = pWnd->HandleMsg(hWnd, msg, wParam, lParam);
ret = &lr;
}
return ret == nullptr ? DefWindowProc(hWnd, msg, wParam, lParam) : *ret;
}

再次重申,该函数在当前状态下运行良好,我只是希望删除看似不安全的变量 lr

最佳答案

我认为你可以这样做,然后你可以删除 retlr 变量。

LRESULT CALLBACK Window::HandleMsgSetup(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)  noexcept
{
if (msg == WM_NCCREATE)
{
const CREATESTRUCTW* const pCreate = reinterpret_cast<CREATESTRUCTW*>(lParam);
Window* const pWnd = static_cast<Window*>(pCreate->lpCreateParams);
SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pWnd));
SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(&Window::HandleMsgThunk));
return pWnd->HandleMsg(hWnd, msg, wParam, lParam);
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}

关于c++ - 将值插入可能为空指针的更简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60960609/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com