const_cast is a special type casting operator in C++ that allows you to remove or add the const/volatile qualifier from pointers or references. It is most commonly used to pass an object to a function that expects a non-const type when the original object was defined with the const modifier.
Usage:
const T& globally), trying to write through the removed const qualifier leads to undefined behavior.void foo(int* p) { *p = 42; } void bar(const int* q) { // Remove const — ONLY if the original object is not const! foo(const_cast<int*>(q)); }
If bar is passed a pointer to int, it is safe to remove const. If it points to a const int, it will lead to UB upon writing.
mutable.“Can you use const_cast to remove const from an object that is a literal or located in read-only memory? What are the consequences?”
Answer: You can remove the const property from a pointer or reference, but if you try to modify a literal or a value located in "read-only" memory (e.g., string literals, static const), it will result in undefined behavior — this can lead to crashes or ignored writes.
Example:
const char* str = "hello"; char* p = const_cast<char*>(str); p[0] = 'H'; // UB: string literal in read-only memory!
Story
In the project, const was removed from fields, then those fields were written to without realizing that a value was passed that was actually const (a global constant) — the application crashed with a segmentation fault on some platforms.
Story
In the code, const_cast was used to bypass const methods without the mutable qualifier: fields of the class were modified inside the const method, leading to hard-to-detect bugs in concurrent access.
Story
Incorrect const_cast on STL container objects (e.g., const std::vector), after which the container was modified — it doesn’t always trigger an immediate error but leads to unpredictable behavior in further operations with the container.