3 ms·
The most succinct way I've heard this explained is: "Const means 'I won't mutate this'. It doesn't mean 'nobody will mutate this'." To do optimizations, compil
by pcwalton 7y ago
The most succinct way I've heard this explained is: "Const means 'I won't mutate this'. It doesn't mean 'nobody will mutate this'."
To do optimizations, compilers really need to know that nobody will mutate a value; just knowing that a particular function won't mutate a value isn't that helpful.
- missblit 7y agoTrue to form, there's multiple forms of const in C++. const on a methond says "I won't mutate the state of this class (except for members explicitly marked as mutable) A const reference says I won't mutate this (unless I const_cast away the constness first) But a const variable actually is a promise to C++, saying "This object will never mutate after initialization ever forever I promise for real this time " (except in the destructor, then it's OK). Confusingly, all together this means you're only allowed to cast away constness if the object wasn't const to start with. ___ Some of the above may be wrong, not a language expert.
- nikbackm 7y agoYou are allowed to cast away const-ness of an actual const object, just as long as you don't modify it.