Why is C++11 constexpr so restrictive?

后端 未结 5 969
死守一世寂寞
死守一世寂寞 2020-12-15 02:27

As you probably know, C++11 introduces the constexpr keyword.

C++11 introduced the keyword constexpr, which allows the user to guarante

5条回答
  •  一向
    一向 (楼主)
    2020-12-15 03:07

    The rules for constexpr functions are designed such that it's impossible to write a constexpr function that has any side-effects.

    By requiring constexpr to have no side-effects it becomes impossible for a user to determine where/when it was actually evaluated. This is important since constexpr functions are allowed to happen at both compile time and run time at the discretion of the compiler.

    If side-effects were allowed then there would need to be some rules about the order in which they would be observed. That would be incredibly difficult to define - even harder than the static initialisation order problem.

    A relatively simple set of rules for guaranteeing these functions to be side-effect free is to require that they be just a single expression (with a few extra restrictions on top of that). This sounds limiting initially and rules out the if statement as you noted. Whilst that particular case would have no side-effects it would have introduced extra complexity into the rules and given that you can write the same things using the ternary operator or recursively it's not really a huge deal.

    n2235 is the paper that proposed the constexpr addition in C++. It discusses the rational for the design - the relevant quote seems to be this one from a discussion on destructors, but relevant generally:

    The reason is that a constant-expression is intended to be evaluated by the compiler at translation time just like any other literal of built-in type; in particular no observable side-effect is permitted.

    Interestingly the paper also mentions that a previous proposal suggested the the compiler figured out automatically which functions were constexpr without the new keyword, but this was found to be unworkably complex, which seems to support my suggestion that the rules were designed to be simple.

    (I suspect there will be other quotes in the references cited in the paper, but this covers the key point of my argument about the no side-effects)

提交回复
热议问题