Dissecting Code

Monday, July 12, 2010

Of constants and R and L values

 

RValue: A value that can appear on the right of an expression only
LValue: A value that can appear on the left of an expression. An LValue is converted to an RValue implicitly. The vice-versa does not hold.

An important point: only LValues can be bound to references to non-constants. A temporary object is a RValue.

Consider the following:

#include <iostream>

using namespace std;

class A
{
public:
~A(){ cout<<"A"; }
};

class B: public A
{
public:
~B(){ cout<<"B"; }
};

B factory()
{
B temp;
return temp;
}


int main()
{
const A& obj = factory();
return 0;
}



This is valid in standard C++, as the const used along with the reference forces the life of the temporary object to the end of the scope of the block rather than the scope of the expression (which is generally the case for temporaries). The const in necessary for performing the above magic. Note here, we have no need for a virtual destructor too!!



Source: http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home