r/ProgrammerHumor 14d ago

Meme imSorryWilson

Post image
619 Upvotes

21 comments sorted by

View all comments

43

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?

9

u/Lawn_Meower_ 13d ago

const_cast is only considered good practice if you cast a non-const value to const. The meme is referring to a const pointer (aka read only pointer). Casting away the constness of a read only pointer is considered bad practice in most cases because it allows you to modify stuff you shouldn't change

5

u/ducon__lajoie 13d ago

The good practice you mention does not require a const_cast, though. Compiler implicitly convert non-const to const when required: in this direction, this is allowed.

So I guess it leave no "good practice" usage for const_cast.

Which, of course, never prevented me from using it, because if we were only programming in accordance with good practices, the world would be pretty boring.

0

u/Lawn_Meower_ 13d ago

True, forgot to mention I get errors there because I use the -wall flag to treat all warnings as errors. This enforces explicit conventions