10

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?

hkBattousai
  • 10,583
  • 18
  • 76
  • 124
  • 1
    May I ask what your purpose with this is? If you need to conform to an API that isn't `const` correct, it would be better to perform the cast at the call site to show why you're casting and minimize the potential for abuse. – Chris Lutz Nov 04 '11 at 02:49

2 Answers2

18

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.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • It is usually safe to use variable names with a '_' Normally compilers use the double underscore, but I often read this generalized rule of not using _ – dau_sama May 15 '14 at 07:54
  • 4
    C++ standard, §17.4.3.1.2: “Each name that contains a double underscore (__) or begins with an underscore followed by an upper- case letter (2.11) is reserved to the implementation for any use.” Don't use reserved identifiers unless you're implementing the compiler or the standard library. – rob mayoff May 15 '14 at 08:43
  • _variableName or _variable_name is then perfectly fine, and I've seen it used in several places with no problem at all. – dau_sama May 15 '14 at 12:52
  • 3
    I don't understand how this is relevant to my answer. – rob mayoff May 15 '14 at 17:16
11

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.