What guarantees does D 'const' provide, compared to C++?

Jonathan M Davis jmdavisProg at gmx.com
Thu Aug 16 19:14:10 PDT 2012


On Friday, August 17, 2012 02:32:01 Mehrdad wrote:
> On Friday, 17 August 2012 at 00:10:52 UTC, Jonathan M Davis wrote:
> > In C++, if you have
> > 
> > const vector<T*>& getStuff() const;
> > 
> > which returns a member variable, then as long as const isn't
> > cast away, you know that the container itself won't have any
> > elements added or removed from it, but you have _zero_
> > guarantees about the elements themselves.
> 
> Right.
> 
> > In contrast, in D,
> > 
> > const ref Array!(T*) getStuff() const;
> > 
> > you would _know_ that not only is the container not altered,
> > but you know that the elements aren't altered either -
> > or anything which the elements point to.
> 
> I'm not so sure about that.
> 
> int yourGlobalCounter;
> 
> struct MyIntPtrArray
> {
> int*[] items;
> 
> MyIntPtrArray()
> {
> items = new int*[1];
> items[0] = &yourGlobalField;
> }
> 
> ref const(int*[]) getItems() const
> {
> ++yourGlobalCounter;
> return items;
> }
> }

What I meant is that you know that nothing was altered through the reference 
that the getter returned. You don't have any such guarantee in C++.

But even if both the constructor and getItems are pure, you could still pass 
the initial value of items in as an argument to the constructor making it so 
that there are potentially references to it outside MyIntPtrArray, which is 
why immutable buys you so much.

So, the optimizations permitted by const alone (and to some extent even with 
pure) do tend to be fairly localized precisely because of the number of ways 
that the const variable could refer to data which is altered by other, mutable 
references to it.

- Jonathan M Davis


More information about the Digitalmars-d mailing list