Beginner: How does an object delete itself?

Steven Schveighoffer schveiguy at yahoo.com
Sun Sep 21 12:12:49 PDT 2008


"nobody" wrote
> Thanks, after some Access Violations in my code I got it to work.
>
> But is this not better?
>
> class Foo
> {
> ...
>     private void deleteMySelf()
>     {
>         for (int i = 0; i < foo.length; i++)
>         {
>             if (foo[i] == this)

A warning for the beginner, be careful with ==.  Use 'is' to check for 
identity (i.e. the exact same instance).  If you don't, you may end up with 
segmentation faults:

               if(foo[i] is this)
>             {
>                 foo[i] = foo[$-1];
>
>                 foo.length--;
>
>                 delete this;
>
>                 break; // is this still necessary?
>             }
>         }
>     }
> ...
> }

Like others, I think this seems like a bad design.  What is wrong with using 
the garbage collector?  And what's wrong with using an external 
class/function to keep track of the Foo's?  If you wanted to change at some 
point your foo array to another type of container instead of an array, your 
function wouldn't work, so Foo is stuck being only in an array.

-Steve 




More information about the Digitalmars-d-learn mailing list