Reputation: 95
My code does not compile.
int foobar()
{
// code
return 5;
}
int main()
{
int &p = foobar(); // error
// code
const int& x = foobar(); //compiles
}
Why does adding the keyword const make the code compile?
Upvotes: 4
Views: 199
Reputation: 279395
As others have said, you can take a const but not a non-const reference to a temporary.
In practice there would be dangers in allowing non-const references to temporaries:
#include <iostream>
void foo(int &i) {
i = 5;
}
int main() {
long l = 4;
foo(l);
std::cout << l << "\n";
}
Now, l
can be implicitly converted to int
, so if a non-const reference to temporary were allowed here, then presumably foo
would be passed a reference to the result of that conversion, same as it actually is if foo
takes const int &
. The assignment would be made to the temporary and then discarded when the temporary is destroyed. That's much more likely to be a confusing bug than it is to be the intended result.
I don't know if there's a neat set of rules to allow non-const references to temporaries in some situations but not in the dangerous/annoying ones, but even if so the C++ standard didn't include them. Note that C++0x has rvalue references, which allow you to do some extra things with temporaries that can't be done in C++03.
Upvotes: 2
Reputation: 92924
In C++ temporaries cannot be bound to non-constant references.
In
int &p = foobar();
The rvalue expression foobar()
generates a temporary which cannot be bound to p
because it is a non-const reference.
const int &x = foobar();
Attaching the temporary to x
which is a reference to const prolongs its lifetime. It is perfectly legal.
Upvotes: 9
Reputation: 272762
Because foobar()
is returning by value; this result is a temporary. You cannot have a non-constant reference of a temporary.
If this were not true, what would this code do?
int &x = foobar();
x = 1; // Where are we writing to?
Upvotes: 4