| The Bellinghman ( |
const_cast is a way of taking something which is meant to be immutable and making it mutable
Well, no.
Well, it can be misused for that, but that's not its purpose.
const_cast<> is meant to allow you to remove a 'const' that has been added to a previously mutable object. If you use it on a genuinely const object, then you are a sinner, and should be cast into the outer darkness, because then you are invoking undefined behaviour.
But if, on the other hand, you have something like:
then you are removing the const previously applied. Here, you have one implementation, with the non-const function forwarding to the one implemented in const terms.
Agreed, const_cast<> can be misused, just as reinterpret_cast<> can be. At least, unlike those poor beggars using C, you can grep for their uses.
Oh, and the classic smelly case is the library APIs that never heard of const: in those cases, you may know that the parameter is not modified, and cast away const. Even so, I'll frequently use a temporary vector of char instead of passing in a std::string::c_str() pointer.
Well, no.
Well, it can be misused for that, but that's not its purpose.
const_cast<> is meant to allow you to remove a 'const' that has been added to a previously mutable object. If you use it on a genuinely const object, then you are a sinner, and should be cast into the outer darkness, because then you are invoking undefined behaviour.
But if, on the other hand, you have something like:
char* thirdchar(char* ptr) {
return const_cast<char*>(thirdchar(const_cast<c har const*>(ptr)));
}
char const* thirdchar(char const* ptr) {
return ptr+2;
}
then you are removing the const previously applied. Here, you have one implementation, with the non-const function forwarding to the one implemented in const terms.
Agreed, const_cast<> can be misused, just as reinterpret_cast<> can be. At least, unlike those poor beggars using C, you can grep for their uses.
Oh, and the classic smelly case is the library APIs that never heard of const: in those cases, you may know that the parameter is not modified, and cast away const. Even so, I'll frequently use a temporary vector of char instead of passing in a std::string::c_str() pointer.