It's rather perplexing, isn't it? It states in TDPL:<br><br>"After you invoke clear, the object is still alive and well, but its destructor has been called and the object is now carrying its default-constructed stated. During the next garbage collection, the destructor is called again, because the garbage collector has no idea in what state you have left the object."<br>
<br>But in what situation would you want to manipulate an object that was already cleared and ready for garbage collection?<br><br><div class="gmail_quote">On Mon, Aug 9, 2010 at 2:16 PM, Steven Schveighoffer <span dir="ltr"><<a href="mailto:schveiguy@yahoo.com">schveiguy@yahoo.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;"><div><div></div><div class="h5">On Sun, 08 Aug 2010 23:16:48 -0400, Andrei Alexandrescu <<a href="mailto:SeeWebsiteForEmail@erdani.org" target="_blank">SeeWebsiteForEmail@erdani.org</a>> wrote:<br>
<br>
<blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">
On 08/08/2010 01:09 PM, Andrej Mitrovic wrote:<br>
<blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">
On Page 187 it states (shortened here for convenience):<br>
"By calling clear(b), you invoke b's destructor, obliterate the object's state with Buffer.init, and call Buffer's default constructor"<br>
<br>
On the next page there's a unittest, and the entire example is this:<br>
<br>
import core.stdc.stdlib;<br>
<br>
class Buffer<br>
{<br>
private void* data;<br>
<br>
// constructor<br>
this()<br>
{<br>
data = malloc(1024);<br>
}<br>
<br>
// destructor<br>
~this()<br>
{<br>
free(data);<br>
}<br>
}<br>
<br>
unittest<br>
{<br>
auto b = new Buffer;<br>
auto b1 = b; // extra alias for b<br>
clear(b);<br>
assert(b1.data is null);<br>
}<br>
<br>
void main() { }<br>
<br>
The assert fails, regardless if there is another reference to the object or not (b1 in this case).<br>
<br>
I've added some writeln()'s (not shown here), and just like the book said, after clear(b), b's destructor gets called, the fields get initialized to .init, and then b's constructor gets called. But the constructor will allocate memory for b1.data again, which means data is not null anymore.<br>
<br>
So I'm guessing the assert code is wrong in the example?<br>
</blockquote>
<br>
Yes, the assert is in error.<br>
</blockquote>
<br></div></div>
Wait wait, when destroying an object manually, the runtime will re-call the constructor? I thought it was just going to assign the TypeInfo's initial value to the class?<br>
<br>
Re-calling the constructor on destruction seems like a horrible mis-feature. Nobody will ever use it.<br>
<br>
-Steve<br>
</blockquote></div><br>