Well, since I'm not describing how const works anymore (although,
it's still different than C++ due to the mutable keyword in C++,
but I digress), I'll go ahead and jump in for this one...
On Friday, 17 August 2012 at 02:30:45 UTC, Mehrdad wrote:
So unless you're expecting the compiler to have the
implementation for the entire class available in order for it
to be able to do any kind of optimization (in which case, it
would have to do a whole bunch of inference to figure out the
aliasing issues, which would amount to what a C++ could try do
just as well), I'm not seeing where the additional
guarantees/potential optimizations are.
I'll tackle the guarantees part and what the compiler could do.
Combine const and pure and here you go:
int global;
struct MyStruct {
int* y;
//this() { } // Stop doing this, it doesn't compile. :P
this(int* z) { y = z; }
auto getValue() const pure {
//++global; // error: cannot access mutable static data
'global'
return this.y;
}
void impureThing() const {
++global;
}
}
void func(ref const(MyStruct) s) pure {
//... can only call pure functions
// s.impureThing(); // error
}
import std.stdio;
void main() {
auto s = MyStruct(&global);
writeln(*s.getValue());
func(s); // func is pure and s will be const ... thus,
writeln(*s.getValue()); // guaranteed to be the same as first
call
}
And this is different than C++. If C++ did have a "pure" keyword
and it worked the same as D's pure keyword, then you still
couldn't make the same inference all the time because C++ allows
const things to internally mutate due to the mutable keyword.
Yeah, you have to start combining features to get the most out of
it, but const + pure allows for more optimizations/reasoning than
const or pure alone.