Beginner: How does an object delete itself?

Janderson ask at me.com
Sun Sep 21 10:40:47 PDT 2008


Simen Kjaeraas wrote:
> 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;
> 

Personally I wouldn't add a method to the class to remove it from a 
list.  Why? Because then your coupling the array to that object.  Its 
far better to write a free function to do it:

void Remove(inout F[] array, F element)
{
	for (int i=0; i<array.length; ++i)
	{
		if (array[i] == element)
		{
			array = array[0..i] ~ array[i+1..$];
			break;
		}
	}
}

Ok, what the hell, lets make it a template:

void Remove(F)(inout F[] array, F element)
{
	for (int i=0; i<array.length; ++i)
	{
		if (array[i] == element)
		{
			array = array[0..i] ~ array[i+1..$];
			break;
		}
	}
}

Now it'll work on any array.

Also if your deleting more then one element in an array you can simply 
iterate backwoods to solve the i shifting to the wrong place problem:

	for (int i=array.length; --i>=0; )
	{
		if (isTypeLookingFor(array[i]))
		{
			array = array[0..i] ~ array[i+1..$];
		}
	}

-Joel


More information about the Digitalmars-d-learn mailing list