liveBook · Manning

Const_cast

As explained in 100 C++ Mistakes and How to Avoid Them

const_cast is a C++ cast expression that adds or removes constness or volatility from an expression's type.

const_cast is the C++ cast for intentionally adding or removing constness or volatility from an expression's type. It communicates that intent more clearly than a C-style cast. section 5.6

Treat it as a narrow legacy-code tool, especially when adapting C and C++ interfaces. Prefer better-designed code that removes the need for casts, and test carefully when incremental fixes are unavoidable. section 5.6

A deliberate but dangerous conversion

const char msg[] = "Hello, world"; char* p = const_cast<char*>(msg); *(p + 1) = 'a'; The named cast makes the conversion visible, but the write still makes this production-style fix risky. Do not use const_cast merely to silence a compiler diagnostic; first check whether the interface or design can preserve constness. section 5.6

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Defines the conversion and demonstrates syntax, but stops short of detailed constness rules or implementation internals.
Examples
Shows a const character array converted to char* and then modified through the resulting pointer.
What it assumes
Assumes basic C++ pointers and const-qualified objects while introducing the purpose of named C++ casts.
What you can do after
Apply it via C++ cast syntax when a narrow compatibility need requires an explicit constness change.
How it connects
Connects const_cast with C-style casts, reinterpret_cast, static_cast, dynamic_cast, and C/C++ interoperability.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.