tags:

views:

126

answers:

1

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'

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.

+10  A: 

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

Prasoon Saurav
http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/
Ugo
@Ugo : Yes, nice article. What's your point?
Prasoon Saurav
Thanks Prasoon Saurav.
Donald
Generally this doesn't result in a compiler *error* though. Usually you get a warning.
Noah Roberts
@Noah Roberts :No, the program is ill-formed. MSVC++ supports this as a non-standard extension and compiles the code.
Prasoon Saurav
@Prasoon The article completes your answer.
Ugo
@Ugo : Okay thanks :)
Prasoon Saurav