const_cast is safe only if you produce a variable that was originally not const . For example, if you have a function that takes a const char * parameter, and you pass the char * modifier, it saves const_cast this parameter back to char * and modifies it. However, if the original variable was actually 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);
Adam Rosenfield Dec 10 '08 at 9:04
source share