This is my learning notes from the course - Mastering C++ Standard Library Features.
Xvalues? Glvalues? Prvalue?
Last time, we talked about Value Categories and Move Semantics in C++, and got some good ideas on lvalues
and rvalues
with examples. Today, let’s dig into more details on value categories in C++.
While knowledge of lvalues
and rvalues
is almost always enough for day-to-day coding, it provides a simplified model of C++ value categories.
Knowledge of the full picture is helpful to get a deeper understanding of move semantics and to write advanced code.
Value Categories (Simplified)
1 | Expression |
Value Categories (Detailed)
1 | Expression |
The terms lvalue
and rvalue
were not enough when designing C++11’s move semantics. Unconditionally moving rvalues
would have caused potentially dangerous behavior, so a more fine-grained model was required.
There now are three leaf value categories:
- lvalues
- xvalues (“expiring rvalues”)
- prvalues (“pure rvalues”)
Both xvalues
and lvalues
are “glvalues
“.
Both xvalues
and prvalues
are “rvalues
“
Glvalue
=> *”has identity”*Rvalue
=> *”cab be moved from”*
Let’s see an example:
1 |
|
There is another example:
1 | int main() |
An xvalue
can be obtained from an lvalue
, but not a prvalue
. That’s why it stands for *”pure rvalue”*.
You can think of prvalues
as rvalues
that are not references (no identity).