Hassan Syed
Hassan Syed

Reputation: 20485

const_cast in constructor acceptable

Is this a valid use of a const_cast ? I am using it in a constructor and it looks as follows:

KeyLiteObject(const char * extension, const char * swap_suffix)
        :    _extension(extension),
             _swap_suffix(swap_suffix),
             _swap_suffix_extension(swap_suffix) 
{
    const_cast<std::string*>(&_swap_suffix_extension)->append(_extension);
}

Yes, the strings will never change.

Upvotes: 1

Views: 360

Answers (2)

Whenever possible avoid the const_cast, and here it is quite possible for any given type. Just create a helper function that takes the two arguments, composes the final value of the constant and use it in the initializer:

// header file
struct test { 
   const type x; 
   test( type const & a, type const & b );
};
// implementation file
namespace {
   type compose( type const & arg1, type const & arg2 ) {
      // calculate the actual value here
   }
}
test::test(type const & a, type const & b) 
      : x( compose(a,b) ) 
{} 

The cost of that is just writting a single free (static or in an unnamed namespace) function in the implementation file, and the result it readable if you choose a proper name for the function. In your case: concatenate or concat would be good choices.

While the use of const_cast in the example will not lead to undefined behavior, I would avoid it for personal reasons. Casts are cumbersome to write in C++ (compare with C or Java) for a reason: so that they will call the attention of the programmer: something weird is going on here! If you start sprinkling casts, then you will get used to seeing them, and they will become natural.

Upvotes: 2

Goz
Goz

Reputation: 62323

Assuming that _swap_suffix_extension is a const std::string then why not just do this:

KeyLiteObject(const char * extension, const char * swap_suffix)
        :    _extension(extension),
             _swap_suffix(swap_suffix),
             _swap_suffix_extension( std::string( swap_suffix ) + std::string( extension ) ) 
{
}

Then you can totally avoid the const_cast ...

Upvotes: 7

Related Questions