Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize reference in initialization list

Tags:

c++

I was told the reference variable must be initialized in the initialization list, but why this is wrong?

   class Foo
    {
    public: 
        Foo():x(0) {      
         y = 1;
        }
    private:
        int& x;
        int y;
    };

Because 0 is a temporary object? If so, what kind of object can reference be bound? The object which can take an address?

Thanks!

like image 456
skydoor Avatar asked Feb 09 '10 20:02

skydoor


People also ask

Why reference members must be initialized using initializer list?

And in in computation phase which typically starts with the '{' of constructor body, if you do an assignment then compiler will complain as the reference member was already intialized. So, your only chance to initialize such member is the constructor initializer list.

How do you initialize a reference variable?

There are three steps to initializing a reference variable from scratch: declaring the reference variable; using the new operator to build an object and create a reference to the object; and. storing the reference in the variable.

Do references have to be initialized?

A reference can be declared without an initializer: When it is used in a parameter declaration. In the declaration of a return type for a function call. In the declaration of class member within its class declaration.


1 Answers

0 is not an lvalue, it's an rvalue. You cannot modify it, but you're trying to bind to a reference where it could be modified.

If you make your reference const, it will work as expected. Consider this:

int& x = 0;
x = 1; // wtf :(

This obviously is a no-go. But const&'s can be bound to temporaries (rvalues):

const int& x = 0;
x = 1; // protected :) [won't compile]

Note that the life-time of the temporary is ended at the completion of the constructor. If you make static-storage for your constant, you'll be safe:

class Foo
{
public:
    static const int Zero = 0;

    Foo() : x(Zero) // Zero has storage
    {
        y = 1;
    }
private:
    const int& x;
    int y;
};
like image 97
GManNickG Avatar answered Oct 01 '22 11:10

GManNickG