Saturday, January 15, 2022

C++: const_cast use case

A third party function that I have to use has an input of type char* which the function does not modify. Normally the type should be const char* but the function writer was a novice it seems. I cannot change it to const char* because it is used in other code that such a change would break. I have a variable that needs to be string so that I can use the flexibility of string. In order to send that string variable into the third party function, I cannot just use  string.c_str() because the compiler would complain that you cannot send a const char* to a function that expects char*. To remove the "constness", I have to use const_cast<char*> (string.c_str()). Example implementation:

Note that the third party function does not modify the input char*. If it did, I could not use const_cast (even tough it would compile) because it would result in undefined behaviour.

No comments:

Post a Comment