Efficiently const_cast-ing a constant reference parameter
-
21-02-2021 - |
Question
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?
Solution
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
.
OTHER TIPS
The first one doesn't make any sense as you cast away constness of _BObject
to only later pass it as a constant reference to BClass
constructor and create a copy, BObject
. The second one does what it means - casts away the constness and keeps the reference to the original object. So if you ask me, the second one is better. Be aware though that const_cast
is not always safe.