Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const_cast vs static_cast

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?

like image 313
Anthony Avatar asked Aug 04 '10 03:08

Anthony


People also ask

What is difference between static_cast and dynamic_cast?

static_cast − This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. dynamic_cast −This cast is used for handling polymorphism.

Why is static_cast better than C style cast?

This static_cast<>() gives compile time checking facility, but the C style casting does not support that. This static_cast<>() can be spotted anywhere inside a C++ code. And using this C++ cast the intensions are conveyed much better.

When should I use const_cast?

const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object. const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point.

What is the difference between static_cast and Reinterpret_cast?

static_cast only allows conversions like int to float or base class pointer to derived class pointer. reinterpret_cast allows anything, that's usually a dangerous thing and normally reinterpret_cast is rarely used, tipically to convert pointers to/from integers or to allow some kind of low level memory manipulation.


2 Answers

Don't use either. Initialize a const reference that refers to the object:

T x;
const T& xref(x);

x.f();     // calls non-const overload
xref.f();  // calls const overload

Or, use an implicit_cast function template, like the one provided in Boost:

T x;

x.f();                           // calls non-const overload
implicit_cast<const T&>(x).f();  // calls const overload

Given the choice between static_cast and const_cast, static_cast is definitely preferable: const_cast should 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.

like image 143
James McNellis Avatar answered Oct 11 '22 22:10

James McNellis


I'd say static_cast is preferable since it will only allow you to cast from non-const to const (which is safe), and not in the other direction (which is not necessarily safe).

like image 39
bcat Avatar answered Oct 11 '22 22:10

bcat