Newbie: copy, assignment of class instances
Simen kjaeraas
simen.kjaras at gmail.com
Thu May 20 16:36:26 PDT 2010
bearophile <bearophileHUGS at lycos.com> wrote:
>> Generally in D it's not a good idea to reassign the reference to a
>> scoped class
>
> You can see it with this little D2 program:
>
>
> import std.stdio: printf;
> class Foo {
> int x;
> this(int xx) { this.x = xx; }
> ~this() { printf("Foo(%d) destructor\n", this.x); }
> }
> void main() {
> scope Foo f1 = new Foo(1);
> Foo f2 = new Foo(2);
> f1 = f2;
> }
>
> It prints just:
> Foo(2) destructor
>
> In general this is not good.
> Bye,
> bearophile
It is indeed not. However, there are two bugs here - first, the
wrong instance's destructor is called. Second, f1's destructor
is never called. Surely this has roots in the same code, but
they're two separate issues.
Basically, with the current system, it must not be the
reference's task to destroy an instance at end of scope, but
the instance itself. The simplest way to fix this is, as you
say, to disallow reassignment of a scope class reference.
--
Simen
More information about the Digitalmars-d-learn
mailing list