Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently const_cast-ing a constant reference parameter

I have a member function which takes a constant reference parameter to another object. I want to const_cast this parameter in order to easily use it inside the member function. For this purpose, which of the following codes is better?:

void AClass::AMember(const BClass & _BObject)
{
    // FORM #1 - Cast as an object:
    BClass BObject = const_cast<BClass &>(_BObject);
    // ...
}

void AClass::AMember(const BClass & _BObject)
{
    // FORM #2 - Cast as a reference:
    BClass & BObject = const_cast<BClass &>(_BObject);
    // ...
}

Can you please compare these two forms? Which one is better in criteria of speed and memory usage?

like image 318
hkBattousai Avatar asked Nov 04 '11 02:11

hkBattousai


People also ask

How do you reference a constant?

A constant reference is an expression that evaluates to the value of the named constant. The simplest constant references are primary expressions—they consist simply of the name of the constant: CM_PER_INCH = 2.54 # Define a constant. CM_PER_INCH # Refer to the constant.

Why would you use const_cast?

const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object. const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point.

Can reference variables be constant?

Once a reference variable has been defined to refer to a particular variable it can refer to any other variable. A reference is not a constant pointer.

What is constant reference to a value?

A constant reference/ Reference to a constant is denoted by: int const &i = j; //or Alternatively const int &i = j; i = 1; //Compilation Error. It basically means, you cannot modify the value of type object to which the Reference Refers.


1 Answers

The first version makes a copy of the object. The second version doesn't. So the second version will be faster unless you want to make a copy.

By the way, all identifiers that start with an underscore followed by a capital letter are reserved for use by the compiler. You should not be using variable names like _BObject.

like image 174
rob mayoff Avatar answered Sep 21 '22 21:09

rob mayoff