Preserving Rvalues with Const References: A C Puzzle
In C , passing rvalues (temporary objects) by const reference is allowed, unlike normal references. Consider the following program:
<code class="cpp">void display(const int& a) { cout << a; } int main() { int a = 5; display(a); // Works with an lvalue display(5); // Also works with an rvalue return 0; }</code>
The program allows passing both lvalues and rvalues to the display function, even though the reference is marked as const. This behavior is puzzling, as const references are typically associated with the preservation of lvalues.
The Const Reference Lifetime Extension
The key to understanding this behavior lies in the semantics of const references in C . A const reference prolongs the lifetime of the referred object until the end of the containing scope. In the case of an rvalue, this effectively prevents the destruction of the temporary object until the const reference goes out of scope.
Example: Prolonging Rvalue Lifetime
In our example, the following occurs when display(5) is called:
This demonstrates how a const reference can keep pointing to an rvalue, allowing it to remain in existence even though it would otherwise be immediately destroyed.
The above is the detailed content of Why Can I Pass Rvalues by Const Reference in C ?. For more information, please follow other related articles on the PHP Chinese website!