When Is a C++ Destructor Called

When is a C++ destructor called?

1) If the object is created via a pointer and that pointer is later deleted or given a new address to point to, does the object that it was pointing to call its destructor (assuming nothing else is pointing to it)?

It depends on the type of pointers. For example, smart pointers often delete their objects when they are deleted. Ordinary pointers do not. The same is true when a pointer is made to point to a different object. Some smart pointers will destroy the old object, or will destroy it if it has no more references. Ordinary pointers have no such smarts. They just hold an address and allow you to perform operations on the objects they point to by specifically doing so.

2) Following up on question 1, what defines when an object goes out of scope (not regarding to when an object leaves a given {block}). So, in other words, when is a destructor called on an object in a linked list?

That's up to the implementation of the linked list. Typical collections destroy all their contained objects when they are destroyed.

So, a linked list of pointers would typically destroy the pointers but not the objects they point to. (Which may be correct. They may be references by other pointers.) A linked list specifically designed to contain pointers, however, might delete the objects on its own destruction.

A linked list of smart pointers could automatically delete the objects when the pointers are deleted, or do so if they had no more references. It's all up to you to pick the pieces that do what you want.

3) Would you ever want to call a destructor manually?

Sure. One example would be if you want to replace an object with another object of the same type but don't want to free memory just to allocate it again. You can destroy the old object in place and construct a new one in place. (However, generally this is a bad idea.)

// pointer is destroyed because it goes out of scope,
// but not the object it pointed to. memory leak
if (1) {
Foo *myfoo = new Foo("foo");
}

// pointer is destroyed because it goes out of scope,
// object it points to is deleted. no memory leak
if(1) {
Foo *myfoo = new Foo("foo");
delete myfoo;
}

// no memory leak, object goes out of scope
if(1) {
Foo myfoo("foo");
}

Will a C# class destructor be called when the class contains static fields?

This should be not a problem. Static fields are not related this way to the instance of the defining type in terms of memory representation.

Check this post for more detailed info: How exactly do static fields work internally?

When is my destructor called in this circumstance? (C#)

Destructor will be called when Garbage collector decides that it have to clean up some old objects. You cannot rely on destructors execution time in .NET

Instead of that you should use Dispose() if you want to clean up some resources when they are not needed (especially when you have any unmanaged resources such as TCP connections, SQL connections etc.)

See Implementing a Dispose Method

When is destructor called for C# classes in .NET?

The equivalent to a C++ destructor is IDisposable and the Dispose() method, often used in a using block.

See http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

What you are calling a destructor is better known as a Finalizer.

Here's how you would use IDisposable. Note that Dispose() is not automatically called; the best you can do is to use using which will cause Dispose() to be called, even if there is an exception within the using block before it reaches the end.

public class MyClass: IDisposable
{
public MyClass()
{
//Do the work
}

public void Dispose()
{
// Clean stuff up.
}
}

Then you could use it like this:

using (MyClass c = new MyClass())
{
// Do some work with 'C'
// Even if there is an exception, c.Dispose() will be called before
// the 'using' block is exited.
}

You can call .Dispose() explicitly yourself if you need to. The only point of using is to automate calling .Dispose() when execution leaves the using block for any reason.

See here for more info: http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.110%29.aspx

Basically, the using block above is equivalent to:

MyClass c = new MyClass();

try
{
// Do some work with 'C'
}

finally
{
if (c != null)
((IDisposable)c).Dispose();
}

Why destructor called after 'return 0'?

What you have here is undefined behavior as per the C++ standard:

As per [class.dtor]/16

Once a destructor is invoked for an object, the object no longer exists; the behavior is undefined if the destructor is invoked for an object whose lifetime has ended (6.8). [ Example: If the destructor for an automatic object is explicitly invoked, and the block is subsequently left in a manner that would ordinarily invoke implicit destruction of the object, the behavior is undefined. —end example ]

You explicitly call the destructor for the automatic object objD with this statement:

objD.~Derived();

And the implicit destruction of the object is invoked at the end of its scope the closing }.

Is a C++ destructor guaranteed not to be called until the end of the block?

You are OK with this - it's a very commonly used pattern in C++ programming. From the C++ Standard section 12.4/10, referring to when a destructor is called:

for a constructed object with
automatic storage duration
when the block in which the object is
created exits

C# Destructor not calling after out of scope

Right, because this isn't C++. The finalizer (not destructor as in C++) is not guaranteed to be called immediately after an object has left its declaring scope, it is called when the GC decides to swoop in and clean up after you.

May I ask why you are using a finalizer to begin with? Are you maintaining references to unmanaged resources which need to be deallocated as deterministically as possible (if so, read up on the IDisposable interface)? The use cases for C# finalizers are few and far between, it's not common to implement them.

Does a C++ destructor always or only sometimes call data member destructors?

When an object is cleaned up in C++, the language will

  • First call the destructor for the class, then
  • Call the destructors for all the fields of the class.

(This assumes no inheritance; if there's inheritance, the base class is then destroyed by recursively following this same procedure). Consequently, the destructor code that you write is just custom cleanup code that you'd like to do in addition to the normal cleanup code for individual data members. You won't somehow "lose" the destructors for those objects being called as normal.

Hope this helps!

Is destructor called implicitly in a overloaded operator delete function?

So in this case, destructor would be called implicitly in a overloaded delete function?

Yes. For a delete expression, (1)the destructor will be invoked firstly, then (2)the apporiate operator delete will be invoked; name lookup and overload resolution will be performed at this stage.

If expression is not a null pointer, the delete expression invokes the destructor (if any) for the object that's being destroyed, or for every element of the array being destroyed (proceeding from the last element to the first element of the array).

After that, unless the matching new-expression was combined with another new-expression (since C++14) the delete expression invokes the deallocation function, either operator delete (for the first version of the expression) or operator delete[] (for the second version of the expression).



Related Topics



Leave a reply



Submit