2

I would like to align a region of memory which will be used for storage to a specific power-of-two alignment using std::align1.

This will apparently invoke UB if the alignment value isn't a fundamental or extended alignment value. Is there any way to check at compile-time (e.g., a static_assert) or at runtime whether the value I want to use is supported?


1 To be clear, I'm also open to std::alignas or std::aligned_storage if they are more flexible or otherwise allow me to safely check what is supported.

BeeOnRope
  • 60,350
  • 16
  • 207
  • 386
  • Hmm. Does "expression fails to be constexpr" trigger SFINAE? If so, I think conditionally invoking UB in a `constexpr` function may be used to detect "is something UB" by having its invokation be in a SFINAE context for a trait, as UB makes something *not constexpr*. But maybe not. – Yakk - Adam Nevraumont May 29 '17 at 02:59
  • It isn't totally clear to me that it is UB either - I can't pay for a copy of the standard, but excerpts I've seen say that some values which are extended, but unsupported alignment values may be _ill-formed_ which would indicate an diagnostic (compile-failure) if I'm not mistaken? – BeeOnRope May 29 '17 at 03:15
  • @Yakk-AdamNevraumont That doesn't work for at least 3 reasons: (1) `std::align` is not constexpr, so any attempt to call it automatically makes the enclosing expression not a constant expression anyway; (2) compilers are not required to diagnose library UB in constant expressions; (3) it does not appear that the evaluation of a construct in a function body of a called function that makes the enclosing evaluation not a constant expression is considered an immediate context failure for SFINAE purposes (see related https://stackoverflow.com/a/75657087/481267) – Brian Bi Mar 19 '23 at 01:08

1 Answers1

0

This is LWG 2377 and it was fixed in C++17. It is noted in the issue description that

it is not possible for the user to even determine whether a value is "a fundamental alignment value or an extended alignment value supported by the implementation in this context"

Thanks to the changes in C++17, you no longer need to worry about checking something that is impossible to check.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312