Wake up Brazil
Wake up Brazil

Reputation: 3411

Is an lvalue reference subjected to an lvalue-to-rvalue-conversion?

I always thought that a reference would be subjected to an lvalue-to-rvalue-conversion, as any other glvalue, when used in an expression. Nevertheless, it seems like, every time a reference is used in an expression, it is handled in bullet point (2.9) of [expr.const]/2 instead of bullet point (2.7) (in C++14, or C++1z).

Take for example the reference r below, used to initialize variable j. Is it subjected to an lvalue-to-rvalue-conversion?

const int i = 1;
constexpr int& r = i
constexpr int j = r;

According to this answer the reference r is handled in bullet point (2.9) of [expr.const]/2 and not in bullet point 2.7, as I would expect. Why is this?

Upvotes: 2

Views: 113

Answers (1)

Brian Bi
Brian Bi

Reputation: 119194

In some contexts the lvalue-to-rvalue conversion occurs because it is explicitly specified to occur in a given context (for example, for the ternary conditional operator, see here). But it is listed in clause 4 so it is an implicit standard conversion; like all other implicit standard conversions, it occurs when needed. For example, a glvalue of type int will be implicitly converted to a prvalue when used as the operand of an arithmetic expression since its stored value is required.

In the case of constexpr int j = r, yes, the glvalue expression r undergoes lvalue-to-rvalue conversion, since this initialization requires the stored value. Although it isn't explicitly specified that reading the stored value of an object invokes an lvalue-to-rvalue conversion, this fact must obviously be true in the context of the entire standard, as well as the C standard, where the term "rvalue" is not used, but instead the analogous concept of the lvalue conversion refers to the conversion of an lvalue into "the value stored in the designated object".

Upvotes: 2

Related Questions