Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
This is the answer of Exercise #8: library trouble.
There are six solutions solutions, as listed below:
const std::string s = "abc***def"; |
Using const is good [1-6], abondoning const-correctness is not.
const std::string s = "abc***def"; |
Don't use C-style casts, but use one of the four more-specific C++ casting keywords [7,8].
const std::string s = "abc***def"; |
The use of reinterpret_cast is nonsense here, because int and const int are closely related. Also, it still will not compile, with the same compile error.
const std::string s = "abc***def"; |
The use of dynamic_cast is nonsense here, because int and const int are not members of the same class hierarchy. Also, it still will not compile, because a dynamic_cast cannot cast from 'const int' to 'int'.
const std::string s = "abc***def"; |
The use of const_cast is my favorite solution. As it is the most correct solution, as all we want to do is to cast away the const. But too bad, it does not compile!
If you know why const_cast does not compile and static_cast does, please send me an email.
const std::string s = "abc***def"; |
I regret that the use of static_cast is the best solution, as a const_cast is more clear. But const_cast does not compile, so one is left to use static_cast.
If you know why const_cast does not compile and static_cast does, please send me an email.
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.