Search code examples
c++arraysraii

Should I delete char arrays in .h files


How do I manage the char array buffer in Test.h?

Test.h

class Test{
public:
    Test();
    ~Test();

    char buffer[255];
};

Test.cc

#include "Test.h"

Test::Test()
{
}

Test::~Test()
{
    // Do I need to delete/free buffer?
}

I understand that when new or malloc are used the memory must be released using delete or free().

Is the char array buffer allocated on the stack for each instance of Test and so does not need to be deleted?


Solution

  • No, you do not need to delete it. Therefore you don't need a destructor (unless you have some other resource which needs to be released)

    The rule is simple: each memory/object obtained with malloc/new/new[] should be freed/destroyed once and only once with the corresponding free/delete/delete[]. Nothing less. Nothing more.

    Also, in modern C++, you rarely need to manage memory resources like this. You would use std::vector or another container, or if you really need pointers, you should use smart pointers, std::unique_ptr and std::shared_ptr.