6

For example:

const int* pc = new const int(3);     // note the const
      int* p  = const_cast<int*>(pc);

*p = 4; // undefined behavior?

In particular, can the compiler ever optimize away the heap-allocated *pc?

If not, does an attempt to modify *pc via p still constitute undefined behavior - and if so, why?

Leo Heinsaar
  • 3,887
  • 3
  • 15
  • 35
  • It's an interesting question but why would you do that? – Thomas Sparber Jun 10 '15 at 12:23
  • related - http://stackoverflow.com/questions/22798558/is-it-legal-to-modify-an-object-created-with-new-through-a-const-pointer – Luchian Grigore Jun 10 '15 at 12:25
  • 1
    const_cast should only be used for interfacing with code that is const-incorrect, for example a function that doesn't modify a string but still takes a char* instead of const char*. Any other kind of use where you modify the object is undefined behavior – KABoissonneault Jun 10 '15 at 12:25

2 Answers2

4

Yes and yes. As to why - because you're modifying a const object.

And good point about the const after new - without it, the code would be legal.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
3

const_cast from const to non-const is only safe if the original pointer was non-const.

If the original pointer is const (as is the case in your example) then the behaviour is undefined.

If you had written

const int* pc = new int(3);

then you could cast away the const-ness of pc.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483