C++ - Static_assert and ability of constexpr functions to evaluate at runtime

拟墨画扇 提交于 2019-12-13 08:11:10

问题


I'm reading about constexpr and static_assert features in C++ and one thing seems confusing to me - I've read that constexpr functions are not necessarily always evaluated during compilation and they can sometimes evaluate at runtime. One thing that bothers me is that static_assert is always checked during compilation. So what happens, if we pass constexpr to static_assert, but compiler chooses to evaluate that constexpr during runtime? Is that even an issue?


回答1:


constexpr functions are not necessarily always evaluated during compilation

It is always evaluated at compile time when it should be, so when its return value is used as const expression.

static_assert is one of this case. constexpr int value = f(); or C<f()> c;(template argument) are other cases.

but in std::cout << f(), it is not required to be computed at compile time.

And in void bar(int p) { const int v = f(p);}, f cannot be evaluated as constexpr (depend of parameter of function which are not (cannot be) constexpr).




回答2:


No, that's not an issue. The standard says that if it evaluates to true the statement has no effect (and if it evaluates to false the program is ill-formed). A consequence of this is that if evaluated at runtime the expression may not have any (observable) side effects (directly or indirectly).

That the compiler is allowed to evaluate constant expressions during runtime doesn't relieve the compiler from the burden of evaluating this expression at compile time anyway. This is because the compiler has to provide diagnostic message if it's not true.



来源:https://stackoverflow.com/questions/34041909/c-static-assert-and-ability-of-constexpr-functions-to-evaluate-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!