Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is const_cast safe?

I can't find much information on const_cast. The only info I could find (on Stack Overflow) is:

The const_cast<>() is used to add/remove const(ness) (or volatile-ness) of a variable.

This makes me nervous. Could using a const_cast cause unexpected behavior? If so, what?

Alternatively, when is it okay to use const_cast?

like image 573
Mag Roader Avatar asked Dec 10 '08 21:12

Mag Roader


People also ask

Should I use const_cast?

If you are careful, you can use const_cast to allow you to retain the const-correctness of your code while still using the library. But you should try to bottleneck those situations to make them as few as possible. tl;dr: const_cast is likely something you should never use.

Why does Const cast exist?

The whole purpose of const is to prevent you from modifying something, that's why your code generates an error. Adding in const_cast is basically telling the compiler to shut up, that you know what you're doing.

Is Const cast undefined behavior?

Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior. So yes, modifying constant variables is undefined behavior.


1 Answers

const_cast is safe only if you're casting a variable that was originally non-const. For example, if you have a function that takes a parameter of a const char *, and you pass in a modifiable char *, it's safe to const_cast that parameter back to a char * and modify it. However, if the original variable was in fact const, then using const_cast will result in undefined behavior.

void func(const char *param, size_t sz, bool modify) {     if(modify)         strncpy(const_cast<char *>(param), sz, "new string");     printf("param: %s\n", param); }  ...  char buffer[16]; const char *unmodifiable = "string constant"; func(buffer, sizeof(buffer), true);  // OK func(unmodifiable, strlen(unmodifiable), false); // OK func(unmodifiable, strlen(unmodifiable), true);  // UNDEFINED BEHAVIOR 
like image 102
Adam Rosenfield Avatar answered Sep 20 '22 14:09

Adam Rosenfield