I'm currently learning about references in C++. Here's something I've been wondering about:
int x = 5;
const int &ref = 3 * x + 1;
My understanding of this is that an anonymous variable is created for this expression 3 * x + 1
to be stored in it. After that, we tie our reference ref
to that anonymous variable. That way we can access it although we can't change the value because its type is const
.
Question: Is there a way we can access this anonymous variable/object apart from using the reference ref
? In general, does C++ allow access to these anonymous objects?
This is called a temporary object (it is not a variable). And it doesn't store the expression, but the result of the expression.
Normally such objects are destroyed at the end of the full expression in which they are created. However if a reference is bound to them immediately, then these objects will live as long as that reference (with some exceptions not applying here).
So yes, you can use ref
here exactly in the same way as if you had written
const int ref = 3 * x + 1;
instead. (With some minor exceptions like decltype(ref)
being different.)
There is no other way to access such objects other than binding a reference to them. But that isn't really a restriction. You can do (almost) everything you can do with the name of a variable also with a reference to a variable/object.