const confusion
Jarrett Billingsley
jarrett.billingsley at gmail.com
Sun May 31 12:36:30 PDT 2009
On Sun, May 31, 2009 at 3:26 PM, Witold Baryluk
<baryluk at smp.if.uj.edu.pl> wrote:
> Hi,
>
> i haven't been here for so long time. So hi all. I'm back again.
>
> I was considering myself as hardcore D hacker, but
> in one point I fail completly. Constness.
>
> Consider this simple code:
>
> module ct;
>
> class C {
> const int a;
> const C b;
>
> this(int a_) {
> a = a_;
> b = null;
> }
> this(int a_, in cord b_) {
> a = a_;
> b = b_;
> }
> C m() const { // line 16
> return b;
> }
> }
>
> void main() {
> C c1 = new C(1);
> C c2 = new C(2, c1);
> c2 = c2.m(); // 23
> }
>
> So I have class C which all methods are "const". So it is completly immutable object,
> one can say.
>
> The problem is with line 16, I define function m which is const (because it
> doesn't change anything). But i'm returing some part of it, so actually somone
> else can change it hypotetically
>
> Actually it is impossible for two reasons:
> * all fields are const,
> * there is no non-consts methods beside constructors.
>
> Of course compiler says here: (dmd 2.028)
> ct.d(16): Error: cannot implicitly convert expression (this.b) of type const(C) to ct.C
>
>
>
> so we change line 16 to:
> const(C) m() const { // line 16
>
> And I can agree that this is correct solution.
>
> but then there is another problem, now in main() function:
> ct.d(23): Error: cannot implicitly convert expression (c2.m()) of type const(C) to ct.C
>
> So now, i need to change all occurence of C to const(C), ok no problem:
> void main() {
> const(C) c1 = new C(1);
> const(C) c2 = new C(2, c1);
> c2 = c2.m(); // line 23
> }
>
> Ok, nice. I can create some alias so it will be easier to use, also.
>
> But now is another problem:
> ct.d(23): Error: variable ct.main.c2 cannot modify const
>
>
> But I wan't to have possibility to change local reference to this class!
> Shouldn't const be about content of object?
>
> Ok, go and just create new variable:
> void main() {
> const(C) c1 = new C(1);
> const(C) c2 = new C(2, c1);
> auto c3 = c2.m(); // line 23
> }
>
> compiler now will be happy.
>
> Ok, it is good for functional style of programing, but consider this:
>
> void main() {
> const(C) c1 = new C(1);
> const(C) c2 = new C(2, c1);
> while (c2 !is null) {
> c2 = c2.m(); // line 23
> }
> writefln(c2.a);
> }
>
>
> So now i need to write tail recursive version of this loop, because compiler
> doen't allow me to reuse variable.
>
> I can write tail recursive loop, but it's:
> * not so efficient
> * users of my library are not familiary with functional programing
> * it's unnatural.
>
> Horiblle.
>
> How to ensure constness of data, and still have possibility of changing references of local variables?
Rebindable.
http://www.digitalmars.com/d/2.0/phobos/std_typecons.html#Rebindable
More information about the Digitalmars-d-learn
mailing list