any news on const/invariant?
Bill Baxter
dnewsgroup at billbaxter.com
Wed Nov 28 15:49:58 PST 2007
Walter Bright wrote:
> Janice Caron wrote:
>> My objection to the existing syntax is more or less solely that
>> const int f();
>>
>> does not declare that f returns a const int, and I think that all
>> newcomers to D will find that /hugely/ confusing.
>
> Const is different in D than in C++, and it will take some getting used
> to for refugees from C++. Anyone who expects it to behave exactly like
> C++ will have difficulty. But if they spend a little time looking at it
> and give it a chance, I think they'll find that it is more consistent,
> intuitive, and usable than C++ const.
>
> Just remember, the const storage class applies to the declaration, not
> the type, and it will make sense.
Here's a class that compiles fine and will probably mostly work.
class Klass {
this() {
array.length = 10;
}
const int elem(int i) {
return array[i];
}
int[] array;
}
But someday when someone tries to call elem() with a const Klass it will
fail to compile.
Also in case anyone else wasn't sure, this is how you declare the common
idiom of const method returning a const reference in the latest D2.008:
const const(int*) get_elem_ptr(int i) {...}
Without the parens it gives "Redundant storage class". (However
declaring it "public public public" still does not create an error...)
Also const int* get_elem_ptr(int i) fails to compile because it tries to
return a mutable pointer from a const method. So that case is ok, but
the one in Klass above seems like trouble brewing to me.
--bb
More information about the Digitalmars-d
mailing list