代码分析警告 (C26426) 和使用 RegisterWindowMessage - 如何解决?

Code analysis warning (C26426) and using RegisterWindowMessage - How to resolve?

代码:

#define UWM_TEST _T("UWM_TEST_{GUID_VALUE_HERE}")
static const UINT UWM_TEST_MSG = ::RegisterWindowMessage(UWM_TEST);

以上工作正常但代码分析抱怨:

C26426: Global initializer calls a non-constexpr function RegisterWindowMessageW (i.22).

上述状态:

The order of execution of initializers for global objects may be inconsistent or undefined. This can lead to issues that are hard to reproduce and investigate. To avoid such problems, global initializers should not depend on external code that's executed at run time and can potentially depend on data that's not yet initialized. This rule flags cases where global objects call functions to obtain their initial values.

我查看了链接页面上的示例,但我不明白我必须做些什么来更正代码分析。


这里也记录了这个问题:https://developercommunity.visualstudio.com/t/Global-initializer-calls-a-non-constexpr/1563190

如果您的 UWM_TEST_MSG 消息仅在特定 class 的成员函数中使用,那么,与其将其定义为(静态)全局常量,不如将其设为 const(但 不是 static)那个 class 的成员,像这样:

class MyClass
{
private:
    #define UWM_TEST _T("UWM_TEST_{GUID_VALUE_HERE}")
    const uint32_t UWM_TEST_MSG = ::RegisterWindowMessage(UWM_TEST);
    ///...
};

否则(如果该消息被更广泛地使用),您可以使它成为您的应用程序的类似(但 public)成员 class:

class MyApp : public CWinApp
{
public:
    #define UWM_TEST _T("UWM_TEST_{GUID_VALUE_HERE}")
    const uint32_t UWM_TEST_MSG = ::RegisterWindowMessage(UWM_TEST);
    ///...
};

在后一种情况下,您需要将所有出现的标识符更改为类似于以下表达式的内容(当然,除非它在 ​​MyApp 的成员内部使用):

static_cast<MyApp*>(AfxGetApp())->UWM_TEST_MSG

(或者,如果您在代码中声明了 extern MyApp theApp;,就像 MFC 程序通常那样,您可以只使用 theApp.UWM_TEST_MSG 而不是上面的表达式。)

无论哪种方式,使消息成为class(无论哪个)的非静态(但仍然是const)数据成员,将避免警告(及其突出显示的潜在问题),因为只有在实例化 class 的对象时才会调用 RegisterWindowMessage