On Thursday, September 29, 2011 01:08:31 Peter Alexander wrote: > On 26/09/11 6:57 PM, Jonathan M Davis wrote: > > On Monday, September 26, 2011 10:26 Steven Schveighoffer wrote: > >> I still don't think this proposal (even one that always lazily > >> initializes) gives enough benefit to be included. Why would you want a > >> constant lazily-initialized value in a non-immutable struct? If this > >> were to mean anything, there would have to be a way to clear the > >> 'set' flag in a mutable struct. > > > > People have been complaining about the lack of logical const. The two > > use > > cases that they seem to have been looking for are the ability cache the > > results of member functions and to lazily load member variables. They > > want to be able to do those things with const and can't (in the case of > > Peter Alexander, he seems to have come to the conclusion that it's bad > > enough that he doesn't use const for anything not related to threaings, > > though I do find that stance a bit odd, since it's _immutable_ that's > > needed for threading, not const). I was merely trying to present a > > solution to lazy loading that worked with const. It would therefore > > partially solve the issues that people have been complaining about. > > Yes, immutable is needed for concurrency, but const has the same > restrictions: if something is const then you can't do lazy loading, > internal caching, or anything else that you might want to do with > logical const. > > Given that: > > (a) I may want/need to use logical const, > (b) I want my code to be const-correct, and > (c) const is incredibly viral in D > > That gives me no choice but to not use const in any situation where I'm > not 100% certain that logical const won't be needed in the future. > Otherwise I may end up trapping myself, forced to resort to undefined > behaviour, or restructure the use of const in a large amount of my code. > I've had to do this even in large C++ code bases more than once, and > it's not fun. With D it would be a lot worse, and that's something I'd > like to avoid.
One suggestion, which you may or may not have thought of and may or may not be acceptable, would be to declare both const and non-const versions of member functions where the non-const version does caching, and the const version uses the cached value if there is one and does the calculation if there isn't (or if it's dirty). It's not perfect, since you could still end up with extra cost in situations where you end up having to call the function multiple times when the variable is const or even just where the first call after the variable has been changed (and the cached value made dirty) is when the variable is const. But it would allow you to use const in many more cases and stil have caching. So, depending on the situation, it could very well solve your problem in at least the general case. - Jonathan M Davis