Re: Destructor: not gauranteed to be called?
- From: "Carl Daniel [VC++ MVP]" <cpdaniel_remove_this_and_nospam@xxxxxxxxxxxxxxx>
- Date: Tue, 31 Jan 2006 08:16:08 -0800
Peter Oliphant wrote:
> I'm programming in VS C++.NET 2005 using cli:/pure syntax. In my code
> I have a class derived from Form that creates an instance of one of
> my custom classes via gcnew and stores the pointer in a member.
> However, I set a breakpoint at the destructor of this instance's
> class and it was never called!!! I can see how it might not get
> called at a deterministic time. But NEVER?
>
> So, I guess I need to know the rules about destructors. I would have
> thought any language derived from C++ would always guarantee the
> destructor of an instance of a class be called at some time,
> especially if created via [gc]new and stored as a pointer.
Why would you think that when C++ makes no similar guarantee for pure native
C++? The destructor for an object on the heap is called when and if you
call delete on a pointer to that object. The situation is no different for
C++/CLI with respect the to destructor (which is IDisposable::Dispose for
C++/CLI).
>
> Yes, I think I can deterministically destruct it via 'delete' and
> setting to nullptr. But the point still kinda freaks me that the
> destructor is no longer gauranteed to EVER be called. I feel like I
> should be worried since it is sometimes important to do other things
> besided freeing up memory in a destructor. In my case I discovered it
> becuase I'm communicating through a serial port which I change the
> baud rate from the current speed, but then changed it back in the
> destructor - only to find out the destructor was NEVER called! Hence,
> the port died, and MY program wouldn't work on subsequent runs since
> it assumed the port had been returned to the same baud (and hence
> couldn't communicate with it anymore).
> So, again, why is the destructor no longer gauranteed to be called,
> and what are these new rules? Or am I being ignorant, and C++ never
> made such assurances. Inquiring minds want to know! : )
They're not new rules - it's the nature of objects on the heap. For managed
object on the GC heap, the Finalizer MAY be called if you don't delete the
object, but the CLR doesn't guarantee that finalizers are ever called
either.
-cd
.
- Follow-Ups:
- Re: Destructor: not gauranteed to be called?
- From: Peter Oliphant
- Re: Destructor: not gauranteed to be called?
- From: Jochen Kalmbach [MVP]
- Re: Destructor: not gauranteed to be called?
- References:
- Destructor: not gauranteed to be called?
- From: Peter Oliphant
- Destructor: not gauranteed to be called?
- Prev by Date: Destructor: not gauranteed to be called?
- Next by Date: Re: static unmanaged object in mixed exe
- Previous by thread: Destructor: not gauranteed to be called?
- Next by thread: Re: Destructor: not gauranteed to be called?
- Index(es):
Relevant Pages
|