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?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With