Why disallow goto in constexpr functions?

前端 未结 2 919
小蘑菇
小蘑菇 2021-02-18 14:41

C++14 has rules for what you can and can\'t do in a constexpr function. Some of them (no asm, no static variables) seem pretty reasonable. But the Stan

相关标签:
2条回答
  • 2021-02-18 14:43

    My understanding is there was a desire to get relaxed constexpr semantics in C++14. A lot of the restrictions that were relaxed were straightforward, but some were more controversial or difficult or [insert adjective of your choice here]. Rather than hold up relaxed constexpr just for the ability to use goto, it was decided to just publish the main changes and hold off on the rest. This seems like a pretty sound choice, since constexpr in C++14 is far more powerful than constexpr in C++11, and not being able to use goto is a fairly minor absence, all things considered.

    That said, there certainly exists the view that having goto in constexpr contexts is both useful and possible. Indeed, the initial proposal for relaxing constexpr allowed it. So maybe all it takes is somebody that wants it to write a proposal to add it. That somebody could be you! was apparently Ville Voutilainen two years ago in N4472, which featured the quite-relevant-to-this-question paragraph of:

    There is unsubstantiated hearsay according to which banning goto in constant expressions is more for taste reasons than technical reasons, meaning that supporting goto in constant expressions isn't particularly hard to implement. I can't say whether that's correct for implementations in general.

    The paper had mixed reception, but now that we have constexpr lambdas, maybe it needs to be revisited. And that somebody could be you!

    0 讨论(0)
  • 2021-02-18 14:57

    constexpr is expected to be evaluated by the front-end of the compiler in some pseudo-interpreted mode or on the abstract syntax tree built in a single pass before any executable code is generated. We know that goto may jump to some part at the end of the function which was not evaluated yet. Hence properly connecting calling and executing goto would force building AST in several passes and jumping out of order between nodes in a tree is still a messy operation that could break some state. So such a construction is not worth the trouble.

    0 讨论(0)
提交回复
热议问题