Inability to dup/~ for const arrays of class objects
Ali Çehreli
acehreli at yahoo.com
Wed May 29 09:04:56 PDT 2013
On 05/28/2013 11:13 PM, Jonathan M Davis wrote:
> On Tuesday, May 28, 2013 22:58:39 Ali Çehreli wrote:
> To make matters worse, what happens when you have a const object
which has a
> reference as a member variable? e.g.
>
> class C
> {
> class D d;
> }
>
> const C c;
Thanks for doing the thinking for me. :) I could not think deeper than
one level yesterday. :)
> Because of the transitivity of const, d must be fully const, and yet
with your
> suggestion, it isn't.
We know the phrase "turtles all the way down". It makes sense. The
interesting thing is, in the case of a class reference, at least due to
syntax, it feels like it is "turtle one level up":
const(C) c = new const(C);
The reason is, the syntax const(C) suggests that the object is const.
(Compared to 'const C c = ...') However, although it looks like const
qualifiying the object, it comes one step up affects the reference as well.
I wondered whether there were more turtles up: :)
void main()
{
class A
{
int i;
this(int i) { this.i = i; }
}
const(A) a1 = new const(A)(1);
const(A) a2 = new const(A)(2);
// The following is a compilation ERROR because it is not
// possible to refer to another object in a non-mutating way:
// a1 = a2; <-- compilation ERROR
// No problem at all! Define a wrapper for a const(A):
class B
{
const(A) a;
this(const(A) a) { this.a = a; }
}
B b1 = new B(a1);
B b2 = new B(a2);
// And use your const(A) through that wrapper:
assert(b1.a.i == 1);
// Maybe we should call this wrapper Rebindable ;)
b1 = b2;
// Yay! :)
assert(b1.a.i == 2);
}
I always fail to remember std.typecons.Rebindable. :( It may be the
solution to OP's issue:
http://dlang.org/phobos/std_typecons.html#.Rebindable
Ali
More information about the Digitalmars-d
mailing list