Destructor called while object is still alive

frame frame86 at live.com
Sat Oct 31 01:00:02 UTC 2020


On Saturday, 24 October 2020 at 11:52:27 UTC, Steven 
Schveighoffer wrote:
> On 10/23/20 4:27 PM, frame wrote:
>> On Friday, 23 October 2020 at 19:39:52 UTC, Steven 
>> Schveighoffer wrote:
>>> On 10/23/20 3:23 PM, frame wrote:
>>>> On Friday, 23 October 2020 at 17:47:34 UTC, Steven 
>>>> Schveighoffer wrote:
>>>>> On 10/23/20 12:48 PM, Ola Fosheim Grøstad wrote:
>>>>>> On Friday, 23 October 2020 at 16:30:52 UTC, Steven 
>>>>>> Schveighoffer wrote:

> Wait, so you use it inside the function after declaring it? And 
> the pointer isn't stored in the stack?
>
> This is different from your original code. Can you post an 
> example of that happening?
>

Sorry, did not notice it.

This is basically the code I posted at begin. A class object 
holds a connection and the whole object can be fetched via a 
static method, returning as class variable. There is no problem 
if the compiler does not detect unreachable code. But for testing 
purposes I just attached a loop below the instantion after 
calling connect() on my new object. After a while, the destructor 
was called while the loop was still running and the object idle 
but alive.

I'm not sure how this have an impact on other scenarios - if the 
object would have started a thread and communicate via socket, 
for example. But I think it would be the same behaviour if the 
compiler want to be smart.

It smells wrong since the object pointer was still valid and 
resides in the current scope and GC should be only allowed to 
purge the object after leaving the scope.

Resource management is no point here. It was just a side effect 
that the connection was closed because the connection was created 
by that class and the complete object was just killed by GC. 
addRoot() also solves the problem for the testcase.

So again, the object was alive and valid - not total out of scope 
or garbage - just unused after that line.



More information about the Digitalmars-d mailing list