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?
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
.