TITLE: deletion and constness (Newsgroups: comp.lang.c++, 11 Aug 98) NARAN: Siemel Naran > "char const*" means that you promise not to change *x, the stuff that x > points to. Deleting x means changing changing x. So it's illegal. But > const_cast removes constness, changing "char const*" to "char*", and now > the delete is legal. BECKER: Pete Becker There was a time when this was the rule. It was such a pain that it was changed: [Note: a pointer to a const type can be the operand of a delete­expression; it is not necessary to cast away the constness (5.2.11) of the pointer xpression before it is used as the operand of the delete­expression. ] NARAN: > If the memory for x was allocated in the constructor with a call to new[], > then I think the const_cast is well defined and delete[] properly delete > the memory. If the memory for x was allocated by another object -- that > is, this object does not own x but just received a pointer to x from > somewhere else -- then the const_cast should result in undefined behaviour. > This is what makes sense to me, because constness can only be casted > away by the object that owns the constness (or at least, this is how it > should be). But can someone please clarify this? BECKER: Be careful to distinguish between a const object and a const access path. For example: const char text[] = "Hello, world!"; const char *ptr = text. *const_cast(ptr) = 'a'; // trouble: text[0] not modifiable Here, text contains const char elements. They are not permitted to be modified. Casting away const to turn ptr into a pointer to non-const char results in undefined behavior. char text[] = "Hello, world!"; const char *ptr = text; *const_cast(ptr) = 'a'; // OK Here, text contains modifiable char elements. You can cast away the const in ptr and modify elements of text, because those elements are in fact modifiable.