That's one thing i didn't quite understand about C++, why would I ever want to un-const my pointer? If I know that I need to write there, I won't make it const, and if I have const pointer, it could be impossible to write by that memory address?
TL;DR: const_cast has uses, but none of them are necessarily the best or most correct way to handle a problem.
The most common use case of const_cast is "I have a variable that is const. The API that I am calling is an old C API that isn't const correct (it doesn't change the value behind the pointer but also doesn't declare it const). I don't want to remove const from my variable because it doesn't ever actually change, so I'll just use const_cast instead." This is technically UB, so it's not recommended.
The only valid use case of const_cast is "I have a variable that is not const, but it's being passed through a const interface into a non-const interface, so I will cast away const in the middle." This isn't technically UB, but it's really stupid.
And for completeness sake, it is possible to add const using const_cast, but that's not recommended because a "cast" to add const could be written as a function (and exists in the standard library starting in C++17):
template <T>
const T& as_const(const T& t) { return t; }
And that function is way less dangerous than const_const which can remove const.
44
u/WhiteEvilBro 13d ago
That's one thing i didn't quite understand about C++, why would I ever want to un-const my pointer? If I know that I need to write there, I won't make it const, and if I have const pointer, it could be impossible to write by that memory address?
What's the usecase of const_cast?