3

Possible Duplicate:
Correct usage(s) of const_cast<>

What is the use of having a const parameter in the function argument and then using const_cast within the function?

Community
  • 1
  • 1
softwarematter
  • 28,015
  • 64
  • 169
  • 263

2 Answers2

9

I've only used const_cast on cases where I have to pass a const parameter to unmodifiable legacy code known to not modify the parameter, i.e. it is in practice const but the signature of the API/function call does not contain the const keyword.

dlanod
  • 8,664
  • 8
  • 54
  • 96
2

You'd only use it when you need to pass that parameter through to a legacy C API that promises not to modify the data.

In no other case should you need to hack away constness with const_cast, and be aware that even after hacking away constness it's still undefined behavior to modify the object; it's just not enforced by your compiler any more, and you take on responsibility for that promise.

stelonix
  • 716
  • 1
  • 5
  • 24
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • Modification after removing the const is only UB if the original object was actually const, but it is still you that takes responsibility for ensuring that. Naturally, you should prefer to pass as non-const in that case, so this still only applies to legacy APIs. – Fred Nurk Feb 15 '11 at 22:35
  • @Fred: I think that that's what I said...? – Lightness Races in Orbit Feb 16 '11 at 14:24