1

Possible Duplicate:
How come a non-const reference cannot bind to a temporary object?

This program:

int fun()
{
    return 1;
}

int main()
{   
    const int& var = fun();

    return 0;
}

My question is why I must put a const befor the var definition? If not ,g++ will give me an error ,goes something like "invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’." what is the 'const' for ?

Community
  • 1
  • 1
Gary Gauh
  • 4,984
  • 5
  • 30
  • 43
  • 1
    Read this article: http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/. – mfontanini Aug 10 '12 at 02:04
  • Well, you've suppressed the error message, but what is your code intended to do? You can't access `var` after its assignment in the code you've given, because it's a reference to a temporary. – Greg Hewgill Aug 10 '12 at 02:05
  • The most simple answer: because otherwise you would have possibility to change your function output, which is of course is nonces. If you have something you can change, when you can set it to non-const reference. This is simple intuitive (and correct) rule how to work with "const". – klm123 Aug 10 '12 at 02:11
  • @Greg: the lifetime of that temporary is extended to the end of the scope. – Cheers and hth. - Alf Aug 10 '12 at 02:31
  • @Cheersandhth.-Alf: Fascinating. I don't think I would have considered even trying that. – Greg Hewgill Aug 10 '12 at 02:37
  • @Greg: it's not much used, but you can find it employed in the original [ScopeGuard implementation](http://www.drdobbs.com/cpp/generic-change-the-way-you-write-excepti/184403758) (Petru Marginean). – Cheers and hth. - Alf Aug 10 '12 at 02:55

1 Answers1

3

In this situation you need const because reference initialization requires a variable with an address, not simply a value. Therefore the compiler must create an anonymous variable which you cannot access other than through the reference; the compiler does not want you to access the variable that you did not declare.

If you would declare the variable explicitly, const would be unnecessary:

int tmp = fun();
int &var(tmp);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523