Andrei Alexandrescu Wrote: > Walter Bright wrote: > > Andrei Alexandrescu wrote: > >> Walter Bright wrote: > >>> Andrei Alexandrescu wrote: > >>>> Bill Baxter wrote: > >>>>> On Tue, Dec 23, 2008 at 11:30 AM, Jerry Quinn > >>>>> <[email protected]> wrote: > >>>>>> This was an interesting read. It would be nice to see a > >>>>>> discussion of how const is going to fit in in terms of > >>>>>> optimization potential, since you can always cast it away. > >>>>> > >>>>> It's basically useless for optimizations I think. > >>>>> Even if the view of the data you have is const, someone else might > >>>>> have a non-const view of the same data. > >>>>> So for instance, if you call any function, your "const" data could > >>>>> have been changed via non-const global pointers to the same data. > >>>>> > >>>>> --bb > >>>> > >>>> Const is still useful because inside a function you know for sure > >>>> that another thread can't modify the data. > >>> > >>> I think you meant immutable. > >> > >> I meant const. > > > > > > In the future, of course, "shared const" means another thread can modify > > it, but "const" means it cannot. Is that what you meant? > > Here's an example: > > int foo(const int*); > > void bar() { > int a = 5; > foo(&a); > // can assume a is unmodified? > } > > There are two issues here. One is that the const guarantees that foo > does not legally change a, so it is useful for an optimization (e.g. > assume that a == 5 after the call to foo). The second issue is that > compilers often assume that a function call may change the stack of the > caller in an arbitrary way. I think it is safe to lift that assumption > for D programs and consider a functions' automatic variables as private > to the function. > > > Andrei
You have to be extremely careful with this kind of thing. If any calls are made with a mutable &a before the call to foo, that optimization can no longer be performed. Also, if a's type changes and used a custom constructor, then that optimization is unreliable for anything other than taking the object's address. If a mutable reference is leaked, all function calls become suspect...
