Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use const_cast?

Tags:

c++

So I'm doing some parsing of C-strings in a function that looks like this:

void parse(const char** params, int numParams);

I wanted to pull some information out of one of the strings stored in params, so I wrote code that looked like this:

char* charPointer;
charPointer = params[0];

The compiler didn't like this and told me that it can't convert from a const char* to a char*. I understand the reasoning behind this (in theory I could write to the address pointed to by charPointer but not by params[0] if it let me) but what I don't understand is how I should be getting around it. I know of two ways to fix this error but I don't know which one is "proper" or really what the differences are between them. The first is:

const char* charPointer;
charPointer = params[0];

And the second method is:

char* charPointer;
charPointer = const_cast<char*>(params[0]);

So which is better and why?

like image 205
quiggy Avatar asked May 10 '26 19:05

quiggy


1 Answers

const_cast is safe only, if pointer is really pointing to something which is non-const, so modifying it is not a problem. If the value is originally const, then using const_cast to get rid of the constness and then writing to it is basically undefined behaviour (for example, other parts of the code may assume value does not change, so your modification only takes effect sometimes).

So definitely use this version:

const char* charPointerr = params[0];

In general, if you need to resort to const_cast, you are probably doing something... if not wrong, then at least ugly. And if you are not sure if it is just ugly or outright wrong, then it's probably wrong.


Example of something where things can go horribly wrong due to undefined behaviour like this:

const bool do_it = true;
bool *ptr = const_cast<bool*>(&do_it);
*ptr = false;

// optimizer probably thinks this is always true
if (do_it) initiate_nuclear_first_strike(); 

While developing using debug build, everything seems to work. Then, release build is deployed (without testing, of course, because in hurry), and BOOM, end of the world. UB is dangerous like that (a side note: effects of UB can also be totally obscure and not as easily understandable as this example).

like image 159
hyde Avatar answered May 13 '26 09:05

hyde