Is compiler allowed to call an immediate (consteval) function during runtime?

前端 未结 2 377
礼貌的吻别
礼貌的吻别 2021-01-02 17:02

This might be a stupid question, but I am confused. I had a feeling that an immediate (consteval) function has to be executed during compile time and w

2条回答
  •  粉色の甜心
    2021-01-02 17:47

    The proposal mentions:

    One consequence of this specification is that an immediate function never needs to be seen by a back end.

    So it is definitely the intention of the proposal that calls are replaced by the constant. In other words, that the constant expression is evaluated during translation.

    However, it does not say it is required that it is not seen by the backend. In fact, in another sentence of the proposal, it just says it is unlikely:

    It also means that, unlike plain constexpr functions, consteval functions are unlikely to show up in symbolic debuggers.


    More generally, we can re-state the question as:

    Are compilers forced to evaluate constant expressions (everywhere; not just when they definitely need it)?

    For instance, a compiler needs to evaluate a constant expression if it is the number of elements of an array, because it needs to statically determine the total size of the array.

    However, a compiler may not need to evaluate other uses, and while any decent optimizing compiler will try to do so anyway, it does not mean it needs to.

    Another interesting case to think about is an interpreter: while an interpreter still needs to evaluate some constant expressions, it may just do it lazily all the time, without performing any constant folding.

    So, as far as I know, they aren't required, but I don't know the exact quotes we need from the standard to prove it (or otherwise). Perhaps it is a good follow-up question on its own, which would answer this one too.

    For instance, in [expr.const]p1 there is a note that says they can, not that they are:

    [Note: Constant expressions can be evaluated during translation. — end note]

提交回复
热议问题