Beginner: How does an object delete itself?
Simen Kjaeraas
simen.kjaras at gmail.com
Sun Sep 21 08:41:33 PDT 2008
On Sun, 21 Sep 2008 17:15:22 +0200, nobody <somebody at somewhere.com> wrote:
> Hello. I just started using OOP and had a question.
>
> I have something like this:
>
> class Foo{
> ..
> private void deleteMyself()
> {
> this.delete;
> foo.length--;
> }
> ..
> }
>
> Foo[] foo;
>
> But this obviously doesn't work.
> The problem is, how do I know what position in the array the object is,
> and
> how do I delete it?
> I don't want empty elements in my array.
class Foo
{
...
private void deleteMySelf()
{
for (int i = 0; i < foo.length; i++)
{
if (foo[i] == this)
{
// If order is not important, copy last element of array
to position i
//
// foo[i] = foo[$-1];
//
// If order is important, iterate through rest of array,
moving elements one step forward
//
// while (++i < foo.length)
// {
// foo[i-1] = foo[i];
// }
//
foo.length--;
}
}
delete this;
}
...
}
Foo[] foo;
--
Simen
More information about the Digitalmars-d-learn
mailing list