deprecated delete and manual memory management

Steven Schveighoffer schveiguy at yahoo.com
Tue Apr 26 17:26:03 PDT 2011


On Tue, 26 Apr 2011 20:15:45 -0400, Daniel Gibson <metalcaedes at gmail.com>  
wrote:

> Am 27.04.2011 02:03, schrieb Steven Schveighoffer:
>> On Tue, 26 Apr 2011 19:45:21 -0400, Daniel Gibson
>> <metalcaedes at gmail.com> wrote:
>>
>>> I just noticed something regarding clear():
>>>   struct Bar { ... }
>>>   Bar *b = new Bar();
>>> This compiles without any warning, but doesn't call the destructor:
>>>   clear(b);
>>> This compiles without any warning and actually does what you'd expect,
>>> i.e. calls destructor:
>>>   clear(*b);
>>>
>>> Is this behavior expected/wanted? If not: Is it a known bug? I couldn't
>>> find it in the bugtracker, but maybe I searched for the wrong keywords.
>>
>> Let's start with class references.  Because class references cannot be
>> separated from its reference, you have to finalize the class when
>> finalizing the reference, because there's no way to say "clear what this
>> reference refers to" vs. "clear this reference".  So you have to give a
>> way to finalize a class instance.
>>
>> With pointers, however, you can specify as you say, whether you want to
>> clear the pointer or the struct itself.
>>
>> Now, is it much useful to clear a pointer without clearing what it
>> points to?  I'd say no, clearing a pointer is as easy as doing ptr =
>> null.  So I'm thinking, it should be filed as a bug.
>>
>> The obvious thing to decide is, what should be done on references to
>> references?  If you clear a double pointer, should it go through both
>> pointers?  Or a pointer to a class reference?
>>
>> I'd say no, but you have to take extra steps to ensure it is this way.
>>
>> -Steve
>
> IMHO clear isn't needed for anything but structs and Objects.
> For any simple type or pointer you can just write x = x.init; instead of
> clear(x) or, as you already mentioned, x=null; for pointers.

It is useful for it to work for generic code.

> AFAIK the main purpose of clear() is to explicitly call the destructor -
> and that only makes sense for structs and classes.
> Allowing it for other types (especially pointers) just sneaks in
> non-obvious bugs, especially when it's considered a replacement for
> delete (which calls the destructor for both Object a *struct).

I'm not sure it introduces subtle bugs for things besides pointers.   
Clearing an int should be harmless.

> BTW: clear() has often been mentioned in this NG but isn't documented in
> the Phobos documentation (which is no surprise because clear() doesn't
> have doc-comments).
>
> So I guess I'll report this as a bug.

If you mean that clear has no docs, I already reported that.

http://d.puremagic.com/issues/show_bug.cgi?id=5855

Feel free to report the enhancement request for clear to dereference  
pointers.

-Steve


More information about the Digitalmars-d mailing list