Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data member int reference

I a trying to store int by reference as data member of class. I expected that is object get int by refernce than if I increase the reference from outside its increase the value inside the object.

class A
{
private :
    int& x;

public:
    A(int y) : x(y)
    {
        cout << "A's ctor x = " << x << endl;
    }

    void print()
    {
        cout << "x = " << x << endl;
    }


};

int main()
{
    int i = 8;
    A a(i);
    a.print();
    ++i;
    a.print();
}

The output is :

A's ctor x = 8
x = 8
x = 8

Why x isnt 9?

like image 909
I.Mac Avatar asked Sep 29 '26 14:09

I.Mac


1 Answers

The issue is that you're binding a temporary (the constructor parameter y) to a reference. The lifetime of the temporary is restricted to the constructor, but your reference lives on, becoming a "dangling" reference. This is what a reasonable compiler has to say about the matter:

crap13.cpp:10:18: warning: binding reference member 'x' to stack allocated parameter 'y' [-Wdangling-field]

A(int y) : x(y)

You can "fix" this by making the constructor parameter a reference:

A(int& y) : x(y)

but you must ensure that whatever is passed as argument to the constructor outlives the object being constructed.

like image 125
juanchopanza Avatar answered Oct 01 '26 03:10

juanchopanza