Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::unreachable

      From cppreference.com
      <cpp‎ |utility
       
       
      Utilities library
       
       
      Defined in header<utility>
      [[noreturn]]void unreachable();
      (since C++23)

      Invokesundefined behavior at a given point.

      An implementation may use this to optimize impossible code branches away (typically, in optimized builds) or to trap them to prevent further execution (typically, in debug builds).

      Contents

      [edit]Notes

      Feature-test macroValueStdFeature
      __cpp_lib_unreachable202202L(C++23)std::unreachable

      [edit]Possible implementation

      [[noreturn]]inlinevoid unreachable(){// Uses compiler specific extensions if possible.// Even if no extension is used, undefined behavior is still raised by// an empty function body and the noreturn attribute.#if defined(_MSC_VER) && !defined(__clang__) // MSVC    __assume(false);#else // GCC, Clang    __builtin_unreachable();#endif}

      [edit]Example

      Run this code
      #include <cassert>#include <cstddef>#include <cstdint>#include <utility>#include <vector> struct Color{std::uint8_t r, g, b, a;}; // Assume that only restricted set of texture caps is supported.void generate_texture(std::vector<Color>& tex,std::size_t xy){switch(xy){case128:[[fallthrough]];case256:[[fallthrough]];case512:/* ... */        tex.clear();        tex.resize(xy* xy, Color{0,0,0,0});break;default:        std::unreachable();}} int main(){std::vector<Color> tex;    generate_texture(tex,128);// OKassert(tex.size()==128*128);    generate_texture(tex,32);// Results in undefined behavior}

      Possible output:

      Segmentation fault

      [edit]See also

      [[assume(expression)]]
      (C++23)
      specifies that theexpression will always evaluate totrue at a given point
      (attribute specifier)[edit]
      informs the compiler that a pointer is aligned
      (function template)[edit]
      C documentation forunreachable

      [edit]External Links

      1. GCC docs:__builtin_unreachable
      2. Clang docs:__builtin_unreachable
      3. MSVC docs:__assume
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/unreachable&oldid=178606"

      [8]ページ先頭

      ©2009-2025 Movatter.jp