Regularly uses const_cast as an acceptable design tool?

I looked at the type of code below, and although I have a personal answer to the question (*), I would like to receive comments from C ++ / design experts.

For some reason Data, this is an object with a non-modifiable identifier and a mutable value:

class Data
{
   const Id    m_id ;        // <== note that m_id is a const member variable
   Value       m_value ;

   Data(const Id & id, const Value & value) ;

   Data(const Data & data) ;
   Data & operator = (const Data & data) ;

   // etc.
} ;

The choice of design became the choice of language, since the identifier was declared constat the class level (**) in order to avoid its (accidental) modification even from within the class functions ...

... But, as you can see, there is a copy-destination operator, which is implemented as:

Data & Data::operator = (const Data & that)
{
   if(this != &that)
   {
      const_cast<Id &>(this->m_id) = that.m_id ;
      this->m_value                = that->m_value ;
   }

   return *this ;
}

The fact that the copy assignment operator is not constant makes this code safe (the user can only legally call this method a non-constant object without causing undefined behavior).

const_cast, const const ++?

:

  • ( operator =)
  • , const_cast (, / / ), .

, , " ". ++ / /.

, mutable ( ++ 98) , , - , . , mutable ( ++ 11 post- " const mutable" Herb Sutter) .

(*) , .

(**) const (.. , )

+4
3

cppreference:

, const_cast , , const volatile undefined.

, , . - const, . .

const_cast - const ( const, , const_cast).

+6

, , , const.

, "" , accessor, const-, .

, , "" , const_cast < > , . , . ( const_cast < > - ?).

- , "" , , "".

0

. missuse - .

- , . . . - , .

0

All Articles