Wrong const. He's talking about the gcc function attribute extension, which most of the time is too strict, so recommending its general use isn't a great idea.
C++ const has no effect on optimization, since it can be casted away.
And being aware of aliasing issues is a good idea in general; nothing the compiler does can fix this in the general case (e.g. if computeWidth() is located in an external shared library it's basically impossible for the compiler to determine that it can't modify m_cachedWidth)
"And being aware of aliasing issues is a good idea in general; nothing the compiler does can fix this in the general case (e.g. if computeWidth() is located in an external shared library it's basically impossible for the compiler to determine that it can't modify m_cachedWidth)"
This is of course, false, it would be more accurate to say "in most open source compilers, ....".
Doing compile/dynamic link/ analyze based points-to analysis is at least 15 years old (papers published), and likely much older.
There is nothing that fundamentally stops the compiler from knowing things about external shared libs. At some point, the binary is being linked against those libs. You can store the necessary info in those libs, and then use it at link time
(This is in fact, one of the premises of LLVM and having a good, cheap, complete on-disk representation).
In any case, in this example,
1. you don't need the function attribute, just the normal C++ function modifier (It's too early to remember if that is the right C++ terminology) would do, since m_cachedWidth is clearly a member.
Link time for shared libraries is run-time, so unless you're advocating everything be JITed the compiler still cannot know in the general case whether an external function modifies random memory.
1. I'm relatively sure that const member functions are still allowed to write into pointers that could potentially lead back to the object.
2. No way to know that just from the source. No way to know it's a member function either - if it isn't then 1. is irrelevant.
C/C++ const has no effect on optimization, unless it's on a global/static object and the compiler can see the original declaration.
I'm not going to look it up in the C++ spec, but in C it's only undefined behavior if the original object was const, and it would make sense for C++ to be the same.
But if you have a const reference to a non-const object, it's legal to use a const_cast to remove the const part. This is the more likely scenario, since most objects aren't const.