Temporary Variables: Runtime rvalue Detection (Page 1 of 4 )
The more precisely the position is determined,
The less precisely the momentum is known in this instant,
And vice versa.
[Heisenberg, uncertainty paper, 1927]
C++ Beyond the limits
Each time when I think that something is simple and easy to understand, I discover there are new depths to explore. The previous four articles touched upon a "simple" subject: Temporary Variables –- and I now consider topics only to be as simple as you want them to be.
Reading other articles and books, I came across the terms lvalue and rvalue. Quickly I discovered these were the official terms for what I had previously known as temporary variables or even unnamed objects. To fully understand their effect it was quite useful to write some simple test code in order to make them appear so we could gain some insight into when the compiler creates and destroys them.
Then you discover there are no single simple solutions to make the problems go away. Whenever a solution appears, another problem appears with it hand in hand. This makes sense of course: if there were a simple solution, the Standards Committee would have probably enforced it long ago. So from "Object Slicing" to "Return Value Optimization" it becomes clear that there is always more than meets the eye.
Some time ago I stumbled upon an article that showed me how deep this temporary rabbit hole can really go. It is an excellent article written by Eric Niebler: “Conditional Love: FOREACH Redux” [Niebler]. This article explains how the BOOST_FOREACH macro works and which tricks have to be pulled to make it work.
Since I have been approaching rvalues from different angles in these articles, I wanted to conclude with an explanation of how you can test whether a variable is temporary or not. The following is an abstract of Eric Niebler’s article and explains how you can test whether a variable is an rvalue or not by using the ternary conditional operator.
Please note that the following code was tested successfully on gcc 3.3.3 but doesn’t work with the Visual C++ Compiler.