Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does empty destructor do?

Tags:

c++

destructor

I heard that empty destructor doesn't do anything and calling it doesn't remove the object. But in the code:

#include <iostream>
#include <set>


class a
{
public:
    ~a() 
    {}
std::set <int> myset;
};

int main()
{
a object;
object.myset.insert(55);
object.~a();
object.myset.insert(20);
std::cout << object.myset.size();
}

I get: "* glibc detected * /.app: double free or corruption (fasttop):" and then "ABORT".

If it matters I have c++11 flag enabled. So what does empty constructor actually do? It does something and I read it doesn't.

like image 606
user1873947 Avatar asked Feb 06 '13 19:02

user1873947


People also ask

What is an empty destructor in C++?

If the destructor does not need to clean up any dynamically allocated memory (that is, we could reasonably rely on the destructor the compiler gives us), will defining an empty destructor, ie. Foo::~Foo() { }

What does a destructor delete?

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

What happens if destructor is not defined C++?

If destructor is not declared, compiler will generate destructor, that will call destructors of all members of object. Leak can be only if you are working with raw-memory (C files, memory allocation etc).

Does destructor free memory?

This operator calls the destructor after it destroys the allocated memory. This function only frees the memory from the heap. It does not call the destructor.


1 Answers

Your destructor may look empty, but it's actually destructing the member variables. In this case, it's destructing myset, so the subsequent insert(20) is crashing.

If your class had no non-POD member variables then the empty destructor would truly do nothing.

like image 197
Lily Ballard Avatar answered Oct 02 '22 06:10

Lily Ballard