我正在查看一些有关无法访问的代码的自定义代码。简而言之,我有一个宏,将某些代码标记为逻辑上无法访问。可以用作:
int boolToInt(bool b)
{
switch (b)
{
case true: return 1;
case false: return 0;
}
MY_UNREACHABLE("All cases are covered within the switch");
}
类似地,我试图在编译器已经知道代码不可访问的位置重用此宏。
while (true)
{
if (++i == 42)
return j;
// ...
}
MY_UNREACHABLE("Infinite loop that always returns/continues, never breaks");
也就是说,在某些情况下,MSVC仍会在无法访问的宏内对自定义处理发出无法访问的代码警告。简化版本如下:
// MSVC: cl.exe /std:c++latest /W4
// Clang: clang++ -O3 -std=c++2a -stdlib=libc++ -Weverything
#ifdef __clang__
#pragma clang diagnostic ignored "-Wc++98-compat"
#pragma clang diagnostic ignored "-Wmissing-prototypes"
#pragma clang diagnostic warning "-Wunreachable-code"
#else
#pragma warning( default: 4702 )
#endif
#ifdef __clang__
#define DISABLE_WARNING_UNREACHABLE _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wunreachable-code\"")
#define REENABLE_WARNING_UNREACHABLE _Pragma("clang diagnostic pop")
#else
#define DISABLE_WARNING_UNREACHABLE __pragma(warning(push)) __pragma(warning( disable : 4702 ))
#define REENABLE_WARNING_UNREACHABLE __pragma(warning(pop))
#endif
[[noreturn]] void g();
#define MY_UNREACHABLE(msg) DISABLE_WARNING_UNREACHABLE; g() REENABLE_WARNING_UNREACHABLE
[[noreturn]] void my_exit(int);
[[noreturn]] void f()
{
my_exit(0);
//g(); // Test if warning works without the macro
MY_UNREACHABLE("Custom message");
}
Reproduction at Compiler Explorer
据我从[Microsoft文档](https://docs.microsoft.com/en-us/cpp/preprocessor/pragma-directives-and-the-pragma-keyword?view=vs-2019)的了解,我应该能够将__pragma
与该警告推送/弹出窗口一起使用,以在宏调用内禁用此警告。 (它甚至有一个这样做的例子)
为了抑制MSVC中的警告,应在此处进行哪些更改?