【问题标题】:Emulating GCC's __builtin_unreachable in Visual Studio?在 Visual Studio 中模拟 GCC 的 __builtin_unreachable?
【发布时间】:2020-07-03 06:50:14
【问题描述】:

我看到this 的问题是关于在旧版本的 GCC 中模拟 __builtin_unreachable。我的问题正是如此,但对于 Visual Studio (2019)。 Visual Studio 是否有 __builtin_unreachable 的等价物?可以模仿吗?

【问题讨论】:

    标签: c++ visual-studio visual-c++ c++17 visual-studio-2019


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      顺便说一句,在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
      

      用法:

      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;
      }
      

      【讨论】:

        【解决方案3】:

        Visual Studio 有 __assume(0) 用于此用例。

        【讨论】:

        • 如果这是标准化的就好了。类似于[[unreachable]]
        • @Ayxan 通过的提案实际上是一个函数:std::unreachable()。可能适用于 C++23。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-12
        • 1970-01-01
        • 1970-01-01
        • 2010-09-17
        • 1970-01-01
        • 1970-01-01
        • 2015-12-10
        相关资源
        最近更新 更多