Uh... destructors?

Steven Schveighoffer schveiguy at yahoo.com
Wed Feb 23 07:13:57 PST 2011


On Tue, 22 Feb 2011 18:19:15 -0500, bearophile <bearophileHUGS at lycos.com>  
wrote:

> Steven Schveighoffer:
>
>> I would think malloc and friends should be pure, as well as free.  They
>> can easily simply be marked pure, since they are C bindings.
>
> D even accepts strongly pure functions like:
>
> pure size_t foo() {
>     auto a = new ubyte[1];
>     return cast(size_t)a.ptr;
> }

cast voids all warranties ;)

> For practical purposes D allows pure functions to return dynamic arrays,  
> objects and structs allocated inside them. This is a significant hole in  
> the D idea of purity. I think marking malloc as pure makes the situation  
> worse :-)

Memory allocation has to be allowed inside pure functions.  Otherwise,  
pure functions are too strict and limited.

Allowing malloc is somewhat exceptional because you then must allow free.   
But I see no reason (yet) to disallow free.  If free cannot be pure, then  
malloc cannot be pure.

Note, the 'hole' you refer to is not a bad thing.  A weakly pure function  
allows one to modularize pure functions, whereas prior to this, things  
like sort could not be pure functions, and therefore could not be used  
inside pure functions.  I think the hole allows pure functions to be  
actually usable and easy whereas before they were much too obscure to be  
useful in much code.

> The idea under those ideas is that objects and arrays are usually  
> interesting for the data/semantics they contain, and not for the value  
> of their pointer. If you ignore the value of their pointer, then the  
> hole vanishes. You can't full close this hole, but those ideas help  
> avoid the more blatantly impure semantics inside/from pure functions.

All that is required is to disallow casting.  But casting can allow more  
flexibility, and might actually be necessary in some cases (sometimes, in  
low level languages, the developer knows better than the compiler what  
should be allowed).  A @safe pure function should be what you desire.

> I'd like to patch that hole, but it can't be fully patched. So maybe all  
> this is useless, or worse it makes the language more rigid and not more  
> safe, so it's probably better to not adopt those ideas.

Those rules do not enhance the experience.  The only one which makes sense  
is to disallow casting, but we already have a construct for that: @safe.

-Steve


More information about the Digitalmars-d mailing list