Skip to main content
7 events
when toggle format what by license comment
Jun 18, 2017 at 22:54 comment added BeeOnRope The possible placement of const defined object into read-only memory (more generally, memory marked read-only) and the associated standard language that allows this makes const_cast a possible time-bomb though. mutable has no such issue since such objects could not be placed in read-only memory.
Jun 18, 2017 at 22:48 comment added BeeOnRope The const_cast pattern does fit better in some cases, such as when you want to temporarily modify a member, then restore it (pretty much like boost::mutex). The method is logically const since the final state is the same as the initial, but you want to make that transient change. const_cast can be useful there because it lets you cast away const specifically in that method were you the mutation will be undone, but mutable wouldn't be as appropriate since it would remove const protection from all methods, which don't necessarily all follow the "do, undo" pattern.
Jun 18, 2017 at 22:39 comment added BeeOnRope I don't agree with because it forces the API client to destroy the const protection of the objects. If you were using const_cast to implement mutation of member variables in a const method, you wouldn't ask the client to the do the cast - you'd do it within the method by const_casting this. Basically it lets you bypass constness on arbitrary members at a specific call site, while mutable let's you remove const on a specific member at all call sites. The latter is usually what you want for the typical use (caching, stats), but sometimes the const_cast fits the pattern.
May 23, 2017 at 12:34 history edited URL Rewriter Bot
replaced http://stackoverflow.com/ with https://stackoverflow.com/
Apr 6, 2015 at 0:25 comment added Brian Bi Plus, using const_cast to modify a part of a const object yields undefined behaviour.
Apr 11, 2012 at 9:07 review Suggested edits
Apr 11, 2012 at 12:58
Mar 5, 2010 at 2:34 history answered Dan L CC BY-SA 2.5