Current location: Hot Scripts Forums » Programming Languages » C/C++ » C++ Tip : Binding a Reference to an Rvalue


C++ Tip : Binding a Reference to an Rvalue

Reply
  #1 (permalink)  
Old 06-29-10, 03:58 PM
Learnbyexamples Learnbyexamples is offline
Disabled
 
Join Date: Jun 2010
Posts: 8
Thanks: 0
Thanked 0 Times in 0 Posts
C++ Tip : Binding a Reference to an Rvalue

Rvalues and lvalues are a fundamental concept of C++ programming. In essence, an rvalue is an expression that cannot appear on the left-hand side of an assignment expression. By contrast, an lvalue refers to an object (in its wider sense), or a chunk of memory, to which you can write a value. References can be bound to both rvalues and lvalues. However, due to the language’s restrictions regarding rvalues, you have to be aware of the restrictions on binding references to rvalues, too.
Binding a reference to an rvalue is allowed as long as the reference is bound to a const type. The rationale behind this rule is straightforward: you can’t change an rvalue, and only a reference to const ensures that the program doesn’t modify an rvalue through its reference. In the following example, the function f() takes a reference to const int:

Code:
void f(const int & i);  
int main()  
{  
 f(2); /* OK */  
}
The program passes the rvalue 2 as an argument to f(). At runtime, C++ creates a temporary object of type int with the value 2 and binds it to the reference i. The temporary and its reference exist from the moment f() is invoked until it returns; they are destroyed immediately afterwards. Note that had we declared the reference i without the const qualifier, the function f() could have modified its argument, thereby causing undefined behavior. For this reason, you may only bind references to const objects.
The same rule applies to user-defined objects. You may bind a reference to a temporary object only if it’s const:

Code:
struct A{};  
void f(const A& a);  
int main()  
{  
 f(A()); /* OK, binding a temporary A to a const reference*/  
}
Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
IE DOM reference - No fun at all! hs2006 JavaScript 2 07-26-06 11:07 AM
linker error:undefined reference to ... pnewton C/C++ 0 03-15-06 11:11 PM
How do I pass a hash reference to a subroutine Torbinsky Perl 2 05-23-05 01:35 AM


All times are GMT -5. The time now is 01:15 PM.
vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.