constexpr reference to non-const object

你。 提交于 2019-12-10 09:24:16

问题


Is it permitted to declare a non-const reference as constexpr? Example code:

int x = 1;
constexpr int& r = x;

This is accepted by gcc and clang (I tried several current and past versions of both, back to C++11, and all accepted it). However I think it should not be accepted because C++14 [dcl.constexpr/9] says:

if a constexpr specifier is used in a reference declaration, every full- expression that appears in its initializer shall be a constant expression

and x is not a constant expression.

The language in the latest C++17 draft of [dcl.constexpr] changed and doesn't even mention constexpr references explicitly any more, I can't make head nor tail of what it is trying to say about them.


回答1:


Assuming that x has static storage duration, the lvalue expression x is a perfectly valid constant expression.

If you use x in a context that requires a prvalue, which causes the lvalue-to-rvalue conversion to be applied to it, then the resulting prvalue expression - call it TO_RVALUE(x) - would not be a constant expression, for obvious reasons. But in the case of reference binding, there is no such conversion.



来源:https://stackoverflow.com/questions/43535233/constexpr-reference-to-non-const-object

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