Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much is deleted when you delete a class or struct in c++?

This is just an idle thought I had when reading this other question:

What is the correct way to delete char**

If the chars mentioned in that question had been created inside an object and that object was deleted, would that correctly clean up the pointers as well, or would they be stuck in memory?

like image 272
shieldfoss Avatar asked May 13 '11 09:05

shieldfoss


People also ask

Does Delete Delete the pointer or the object?

The delete operator does absolutely nothing to the pointer itself. The delete operator sends the object pointed to by the pointer back the heap, after running any required destructors. When the delete operator is finished, you a left with a pointer that points to memory you don't own.

How do you delete a structure?

When you want to delete an struct, simply loop through the array to find the one in question, and change to Deleted=1.

Does delete call destructor?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.

How do you delete an object from a class?

In C++, the single object of the class which is created at runtime using a new operator is deleted by using the delete operator, while the array of objects is deleted using the delete[] operator so that it cannot lead to a memory leak.


2 Answers

If you delete an object, the destructor for that object will be called, so you need to do a delete in the destructor. So remember, everything that the class has allocated on the heap has to be freed in the destructor. If it was been allocated on the stack this happens automatically

struct A
{
    A() { std::cout << "A()" << std::endl; ptr = new char[10]; }
    ~A() { std::cout << "~A()" << std::endl; delete []ptr; }
    char *ptr;
};

But be careful, if you are using inheritance, if A inherits from a base class, you need to make the base destructor virtual, or else the destructor in A will not be called and you will have a memory leak.

struct Base
{
    virtual ~Base() {}
};

struct A : public Base
{
    A() { std::cout << "A()" << std::endl; ptr = new char[10]; }
    ~A() { std::cout << "~A()" << std::endl; delete []ptr; }
    char *ptr;
};
like image 141
hidayat Avatar answered Nov 03 '22 12:11

hidayat


They would stuck in the memory. Therefore you need to define Destructor when you make dynamic memory allocation within objects. The D'tor is called when the parent object is about to be delete, and you should explicitly free in the D'tor all the sub-allocated memory.

For more info, look at Wikipedia.

like image 27
Yaakov Shoham Avatar answered Nov 03 '22 12:11

Yaakov Shoham