Effectively const_cast-ing constant reference parameter

I have a member function that takes a constant reference parameter to another object. I want const_cast this parameter to easily use it inside a 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 compare these two forms? Which one is better in terms of speed and memory usage?

+6
source share
2 answers

The first version makes a copy of the object. The second version is no. Thus, the second version will be faster if you do not want to make a copy.

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

+10
source

The first does not make any sense, since you discard the _BObject constant _BObject that you can pass it later as a constant reference to the BClass constructor and create a copy of BObject . The second does what it means - discards a constant and stores a reference to the original object. Therefore, if you ask me, the second is better. Remember that const_cast not always safe.

+9
source

Source: https://habr.com/ru/post/900751/


All Articles