skip to content

In C++, when is writing through a pointer obtained with `const_cast` well-defined, and when is it undefined behaviour?

level: middleimportance: should knowfreq 52%

answer

  1. the object, not the pointer
  2. const access path vs const object
  3. modify a const object: undefined
  4. read-only memory, folded constants

basics

~20 s

Writing through a const_cast result is defined only when the object itself was not created const; const_cast merely removes const from the access path. Modifying an object defined const, such as a const variable or a string literal, is undefined behaviour.

solid answer

~40 s

`const_cast` changes only the type of a pointer or reference; it never changes whether the object is const. The rule that matters is in the declarations clause: any attempt to modify a const object during its lifetime is undefined behaviour. So if a `const char*` points into a non-const `char buf[]`, casting it to `char*` and writing is fine. If it points to a `static const` array, a string literal or an object from `new const T`, the write is undefined: the object may live in read-only memory and trap, or the compiler may have folded its value so later reads ignore the write. The legitimate use is passing const data to a C API that takes `char*` but only reads; if it writes, hand it a copy such as `std::string::data()`.

code

cpp · 14 lines
cpp
#include <cstdio>

static const char kBanner[] = "katajob";
void legacy_upcase(char* s) { s[0] = 'K'; }    // C API that writes

int main() {
    char buf[] = "katajob";
    const char* view = buf;
    legacy_upcase(const_cast<char*>(view));      // defined: buf itself is not const
    std::puts(buf);                              // Katajob

    legacy_upcase(const_cast<char*>(kBanner));   // undefined: kBanner is a const object
    std::puts(kBanner);
}

go deeper

for a junior

Recall that const_cast changes the pointer's type, not the object, and that writing to an object defined const is undefined.

for a middle

Explain the const object versus const access path distinction with the draft's own example, and name read-only placement and constant folding as consequences.

for a senior

In C interop, read the C side before casting away const, and give writing APIs an owned buffer instead of a cast.

for a principal

Require a review note for every const_cast and track the C APIs that force them, so fixing their signatures becomes visible work.

## What `const_cast` actually changes `const_cast<T>(e)` changes the **type of an access path**, a pointer or reference, by adding or removing `const` and `volatile`. It does not touch the object. The object's own constness was fixed when it was created, and the standard keys the rule to that: "Any attempt to modify a const object during its lifetime results in undefined behavior." So there are two different things that can be `const`: - **the object**: `const int limit = 10;`, `static const char kBanner[] = "katajob";`, an object created by `new const T`, a string literal; - **the path to it**: a `const int*` or `const std::string&` that happens to refer to an object that was created non-const. Removing `const` from the path is always allowed. Writing through the result is defined **only if the object itself is not const**. ## The draft's own example The declarations clause gives both cases side by side: ```cpp int i = 2; const int* cip = &i; int* ip = const_cast<int*>(cip); *ip = 4; // defined: *ip points to i, a non-const object const int* ciq = new const int(3); int* iq = const_cast<int*>(ciq); *iq = 4; // undefined behavior: modifies a const object ``` The two casts are identical; only the object differs. ## Why the result is undefined, not just "wrong" Because the compiler may assume a const object never changes, it is free to: - place it in **read-only memory**, so the write traps at run time; in the example below the program was killed by a signal on this machine; - **fold its value** into the code, so later reads keep returning the original value even after a write "succeeded"; - reorder or remove loads of it. None of these is guaranteed, which is the point: undefined behaviour has no defined outcome, and a test that passes proves nothing. ## The legacy API case Porting a C plugin interface, you meet functions that take `char*` but only read, for example a logging hook. Passing a `const char*` there through `const_cast<char*>` is the textbook legitimate use: no write happens, so it does not matter what the object is. The risk is the function you have not read. If the C side ever writes, the call becomes undefined behaviour for callers passing literals or const buffers, while still working for callers passing their own arrays. When the C function **does** write, give it writable storage instead of a cast: 1. copy into a `std::string` and pass `s.data()`; the non-const `data()` overload exists since C++17 (before that, `&s[0]`); 2. or copy into a `std::vector<char>` or a local array sized for the API's contract; 3. keep the original `const` data untouched. ## `mutable` and other exceptions A **`mutable`** data member may be modified even when the enclosing object is const, through a const member function, without any cast; that is the sanctioned way for caches and mutexes inside logically-const objects. Volatile access has its own rules, discussed with registers and hardware. There is no other exemption: `const_cast` does not create one. ## Finding the risky casts in a port In a large C-interop port, the casts that drop `const` are easy to find because they are named: search for `const_cast`, then for C-style casts whose target type lacks a `const` the source had, which `-Wcast-qual` reports in both GCC and Clang. For each hit, the review question is always the same two-step check: 1. does the callee, or anything it calls, ever write through the pointer; 2. if it does, can the object behind it ever be a const object, a literal or read-only data? A "no" to the first or the second makes the cast safe; two "yes" answers are a latent crash. ## Quick reference | Object | Access path | Write through `const_cast` | |---|---|---| | `char buf[]` | `const char*` | defined | | `std::string s` (non-const) | `s.data()`, already `char*` since C++17 | no cast needed | | `static const char k[]` | `const char*` | undefined behaviour | | string literal `"PING"` | `const char*` | undefined behaviour | | `new const T` | `const T*` | undefined behaviour | Do not route the string case through `c_str()` and a `const_cast`: the C++23 library wording says the program shall not modify the characters reached through `c_str()` or the const `data()`, so that write is undefined even though the string itself is not const. The non-const `data()` exists precisely for writing, with one limit: the terminating null may only be overwritten with a null.

  • Is `const_cast` on `this` inside a const member function ever acceptable?
    Only if the object was not created const, and that is something the member function cannot know: a `const Widget w;` would make the write undefined. For caches, counters or mutexes inside logically-const objects, declare the member `mutable` instead, which the language allows to change even in a const object.
  • Why might a write through `const_cast` to `const int limit = 10;` appear to do nothing?
    The compiler may treat `limit` as the constant `10` everywhere it is read, so later reads never load memory; the write, if it executes, changes a location nobody reads. That is one possible face of undefined behaviour, alongside a crash from read-only memory; neither is promised.

  • Any write through a const_cast pointer is undefined behaviour.
  • const_cast makes the object itself writable.
  • If the program does not crash, the write was legal.
  • A string literal can be modified once const is cast away.
  • const_cast is the right tool for a C API that writes into the buffer.