[英]Emulating GCC's __builtin_unreachable in Visual Studio?
I have seen this question which is about emulating __builtin_unreachable
in an older version of GCC. My question is exactly that, but for Visual Studio (2019).我看到这个问题是关于在旧版本 GCC 中模拟
__builtin_unreachable
的。我的问题正是这个问题,但针对的是 Visual Studio (2019)。 Does Visual Studio have some equivalent of __builtin_unreachable
? Visual Studio 是否有一些等效的
__builtin_unreachable
? Is it possible to emulate it?可以效仿吗?
MSVC has the __assume
builtin which can be used to implement __builtin_unreachable
. MSVC 具有
__assume
内置__assume
,可用于实现__builtin_unreachable
。 As the documentation says, __assume(0)
must not be in a reachable branch of code, which means, that branch must be unreachable.正如文档所说,
__assume(0)
不能位于可访问的代码分支中,这意味着该分支必须不可访问。
By the way, before std::unreachable() is available you can implement it as a compiler-independent function, so that you don't have to define any macros:顺便说一句,在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
Usage:用法:
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;
}
对于此用例,Visual Studio 具有__assume(0)
。
C++23 will have std::unreachable as a cross-platform alternative. C++23 将std::unreachable作为跨平台的替代方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.