Domanda

The following code executes normally (see here):

#include <iostream>

struct A {
    int i;
    A():i(1){}
    operator int&() { return i; }
};

int& rri = A();

int main()
{
    int& ri = A();
    std::cout << ri << '\n';
    std::cout << rri << '\n';
}

It prints

1
1

as expected. However if I comment out the first two statements in main(), leaving just

std::cout << rri << '\n';

the code prints 0.

Edit:

Let's assume the problem is with my code. But then I ask: what is the purpose of the third bullet point in 8.5.3/5 in the Standard, which I copied below:

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:

  • If the reference is an lvalue reference and the initializer expression

    • is an lvalue (but is not a bit-field), and “cv1 T1” is reference-compatible with “cv2 T2,” or

    • has a class type (i.e., T2 is a class type), where T1 is not reference-related to T2, and can be converted to an lvalue of type “cv3 T3,” where “cv1 T1” is reference-compatible with “cv3 T3” (this conversion is selected by enumerating the applicable conversion functions (13.3.1.6) and choosing the best one through overload resolution (13.3)),

    then the reference is bound to the initializer expression lvalue in the first case and to the lvalue result of the conversion in the second case (or, in either case, to the appropriate base class subobject of the object). [ Note: The usual lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are not needed, and therefore are suppressed, when such direct bindings to lvalues are done. —end note ]

È stato utile?

Soluzione

Undefined behaviour: ri and rri are both initialised to refer to a member of a temporary, which is immediately destroyed.

The dangling reference points to some bit of memory which might be reused by another object, in which case you might see data from that object. Or you might see some other kind of undefined behaviour.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top