3 ms·
You have it backwards. const is your promise to the compiler that the object won't change. It doesn't care whether you const_cast, implement the function in for
by MauranKilom 7y ago
You have it backwards. const is your promise to the compiler that the object won't change. It doesn't care whether you const_cast, implement the function in fortran or use raw assembly to mess with that object - it assumes that you don't. If you modify a const object in any way you have violated the C++ standard and get UB in return.
Now, the tricky part is that const objects (i.e. objects declared as const) enjoy these optimization benefits, but the compiler usually cannot prove that a reference or pointer to const actually refers/points to a const object. Taking a const pointer to a non-const object, casting away the constness again and then modifying the object is totally legal.
Since the former case (objects declared const) is much rarer than the latter case (working on const object pointers/references) the compiler cannot often optimize based on const.
- gpderetta 7y agoInterestingly, top level cost does not guarantee immutability, but any const member reachable from that reference is in fact guaranteed to be immutable: ergo: template<class T> struct deep_const { const T value; }; template<class T> const deep_const& freeze(const T&) { /* magic */ } template<cass T> const T & thaw(deep_const<T> const&) { /* more magic */ } magic and more magic left as an exercise for the reader. edit: I do not think either GCC or clang take advantage of that though, so currently it is just a curiosity. edit: missed actual const keywords /facepalm