To add const to a non-const object, which is the prefered method? const_cast<T> or static_cast<T>. In a recent question, someone mentioned that they prefer to use static_cast, but I would have thought that const_cast would make the intention of the code more clear. So what is the argument for using static_cast to make a variable const?
To add const to a non-const object, which is the prefered method? const_cast<T> or
Share
Don’t use either. Initialize a const reference that refers to the object:
Or, use an
implicit_castfunction template, like the one provided in Boost:Given the choice between
static_castandconst_cast,static_castis definitely preferable:const_castshould only be used to cast away constness because it is the only cast that can do so, and casting away constness is inherently dangerous. Modifying an object via a pointer or reference obtained by casting away constness may result in undefined behavior.