www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is "delete" really going away?

reply "Minas Mina" <minas_mina1990 hotmail.co.uk> writes:
I think having the delete keyword for classes was a very good 
thing, altough I don't know the problems it has for the GC and 
probably other things.

Consider this scenario:
class Base
{
	// ...
}

class Derived : Base
{
	// ...
	
	FILE *f;
	
	this()
	{
		f = fopen(...);
	}
	
	~this()
	{
		fclose(f);
	}
}

void main()
{
	Base *b = new Derived();
	delete b; // call the copy constructor
	
	b = // something else...
}


Having a destructor and that you know when is going to be called 
is VERY useful!
So by removing the "delete" keyword, what happens? We won't have 
a way to destroy objects in a predictable way anymore? (I'm not 
talking about structs in any way).

Thanks
Jul 29 2012
next sibling parent Timon Gehr <timon.gehr gmx.ch> writes:
On 07/29/2012 03:03 PM, Minas Mina wrote:
 Having a destructor and that you know when is going to be called is VERY
 useful!
 So by removing the "delete" keyword, what happens? We won't have a way
 to destroy objects in a predictable way anymore? (I'm not talking about
 structs in any way).

 Thanks
import std.stdio; void main(){ auto c = new class{ ~this(){writeln("destroyed!");} }; version(future) destroy(c); else clear(c); } clear is being renamed to destroy starting from the next release IIRC.
Jul 29 2012
prev sibling parent reply "Simen Kjaeraas" <simen.kjaras gmail.com> writes:
On Sun, 29 Jul 2012 15:03:09 +0200, Minas Mina  
<minas_mina1990 hotmail.co.uk> wrote:

 Having a destructor and that you know when is going to be called is VERY  
 useful!
 So by removing the "delete" keyword, what happens? We won't have a way  
 to destroy objects in a predictable way anymore? (I'm not talking about  
 structs in any way).
You should instead use destroy(instance). It will call the object's destructor and clear its vtable. If you need to release the memory too, you should probably use malloc and free, and std.conv.emplace. If you have a GC allocated object and want to reclaim the memory, core.memory.GC.free should do that. But if this is something you need to do, you've probably done something wrong somewhere. Oh, apparently, destroy() is called clear in 2.059. It's being renamed in the next version. -- Simen
Jul 29 2012
parent reply "Minas Mina" <minas_mina1990 hotmail.co.uk> writes:
Thanks for the answers.

So clear() or destroy() in 2.060 be used to call the destructor, 
but the actual memory of the object won't be freed, right?

Is this is true, why wasn't "delete" changed to behave like 
destroy()?
Jul 29 2012
parent "bearophile" <bearophileHUGS lycos.com> writes:
Minas Mina:

 Is this is true, why wasn't "delete" changed to behave like 
 destroy()?
Maybe to not silently break D code that uses delete, and allow easier future changes in the library/runtime code that implements destroy(). Bye, bearophile
Jul 29 2012