How much is deleted when a class or structure is deleted in C ++?

This is just an empty thought I read while reading this other question:

What is the correct way to remove char **

If the characters mentioned in this question were created inside an object and this object was deleted, would it clear pointers correctly or would they be stuck in memory?

+5
source share
6 answers

If you delete an object, the destructor for that object is called, so you need to do the deletion in the destructor. Therefore, remember that everything that the class allocates to the heap must be freed in the destructor. If it was 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;
};

, , A , , A , .

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;
};
+6

. Destructor, . D'tor , , D'tor .

Wikipedia.

+3

, .

+1

The pointer must be deleteexplicitly (you or some kind of library wrapper). For instance:

struct A {
  char *p; // assume p = new char[] somewhere;
};

A* pA = new A;
delete pA; // <-- this doesn't clean up char* p
+1
source

An object will clear pointers only if you specifically said it in Deconstructer.

+1
source

If the class is spelled correctly, deleting an instance of this class should free up all the resources allocated by this class.

If a class stores pointers to memory that it does not allocate, unless the documentation indicates otherwise, usually these pointers are not expected to be deleted.

+1
source

All Articles