Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `invalid initialization of non-const reference` mean?

Tags:

c++

templates

When compiling this code I get the following error:

In function 'int main()': Line 11: error: invalid initialization of non-const reference of type 'Main&' from a temporary of type 'Main'

Here's my code:

template <class T>
struct Main
{
    static Main tempFunction(){
       return Main();
    }
};

int main()
{
   Main<int> &mainReference = Main<int>::tempFunction(); // <- line 11
}

I don't understand why? Can anyone explain?

like image 878
Donald Avatar asked Sep 15 '10 17:09

Donald


1 Answers

In C++ temporaries cannot be bound to non-constant references.

Main<int> &mainReference = Main<int>::tempFunction();

Here you are trying to assign the result of an rvalue expression to a non-constant reference mainReference which is invalid.

Try making it const

like image 141
Prasoon Saurav Avatar answered Oct 19 '22 08:10

Prasoon Saurav