94. Avoid casting away const

Summary

Some fibs are punishable: Casting away const sometimes results in undefined behavior, and it is a staple of poor programming style even when legal.

Discussion

Once you go const, you (should) never go back. If you cast away const on an object whose original definition really did define it to be const, all bets are off and you are in undefined behavior land. For example, compilers can (and do) put constant data into ROM or write-protected RAM pages. Casting away const from such a truly const object is a punishable lie, and often manifests as a memory fault.

Even when it doesn’t crash your program, casting away const is a broken promise and doesn’t do what many expect. For example, this doesn’t allocate a ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.