Another Transitive const solution

Alex Burton alexibu at mac.com
Wed Apr 9 15:24:36 PDT 2008


Craig Black Wrote:

> > Goals of transitive const
> > 1. To make the compiler able to perform optimisations based on const.
> > 2. To make a documenting const system that is checked by the compiler and 
> > useful to the programmer.
> >
> > Goal 1 is not achievable as has been shown previously in this group :
> 
> Correct me if I'm wrong, but I read in an article that there are simple 
> optimizations that can be performed by C++ compilers using const.  For 
> example this is preferred:
> 
> const int size = container.size();
> for(int i = 0; i < size; i++) { ... }
> 
> rather than this:
> 
> int size = container.size();
> for(int i = 0; i < size; i++) { ... }
> 
> Because it gives the compiler assurance to know that the size will not 
> change during the loop.
> 
I am not an expert on such things but :
container is likely to be a container like vector<T> which is a template, which allows the compiler to see what is actually in the size() function.
If all we had was an interface to container, then the compiler couldn't assume that there wasn't a perfectly legal mutable member in there that changed each time size was called, or that the result of size is coming from some other class not part of the container.
Both of these are weaknesses that Walter points out with C++ const system, and he is right, but unfortunately transitive const doesn't fix it.

Alex





More information about the Digitalmars-d mailing list