问题
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 Standard also disallows goto
in constexpr
functions, even while it allows other control flow mechanisms.
What's the reasoning behind this distinction?
I thought we were past "goto is hard for compilers".
回答1:
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!
回答2:
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.
来源:https://stackoverflow.com/questions/45266577/why-disallow-goto-in-constexpr-functions