在 Visual Studio 中模拟 GCC 的 __builtin_unreachable?

Ayx*_*xan 5 c++ visual-studio visual-c++ c++17 visual-studio-2019

我见过这个问题,它是关于__builtin_unreachable在旧版本的 GCC 中进行模拟的。我的问题正是如此,但对于 Visual Studio (2019)。Visual Studio 是否有一些等价物__builtin_unreachable?有没有可能效仿呢?

dev*_*oln 7

顺便说一下,在std::unreachable()可用之前,您可以将其实现为独立于编译器的函数,这样您就不必定义任何宏:

#ifdef __GNUC__ // GCC 4.8+, Clang, Intel and other compilers compatible with GCC (-std=c++0x or above)
[[noreturn]] inline __attribute__((always_inline)) void unreachable() {__builtin_unreachable();}
#elif defined(_MSC_VER) // MSVC
[[noreturn]] __forceinline void unreachable() {__assume(false);}
#else // ???
inline void unreachable() {}
#endif
Run Code Online (Sandbox Code Playgroud)

用法:

int& g()
{
    unreachable();
    //no warning about a missing return statement
}

int foo();

int main()
{
    int a = g();
    foo(); //any compiler eliminates this call with -O1 so that there is no linker error about an undefined reference
    return a+5;
}
Run Code Online (Sandbox Code Playgroud)


And*_*hev 5

MSVC 有__assume内置的可用于实现__builtin_unreachable. 正如文档所述,__assume(0)不得位于代码的可到达分支中,这意味着该分支必须不可到达。