c++pointersmemory-leaksownership-semantics

Is there a way to delete a pointer that has not been assigned with new operator in the destructor? If so, should I delete it in the destructor?


For example,

class Test{
private:
   int* foo;
public:
   Test(int* foo){this->foo = foo;}
}

In this case, is there any way I can delete foo in the destructor? Will I have to delete foo in the destructor or at least set it to nullptr?


Solution

  • Sure, you can. It is legal syntax. And depending on the rest of your program, it might do what you want, or it might be a double delete (delete the same pointer twice) which corrupts the heap and will lead to an eventual crash. (Debugging compilers might catch this.)

    One of the reasons the C++ standard template library gave us shared_ptr and unique_ptr is that memory management by hand is hard. It isn't impossible; people did it (or tried to) for many, many years. But it was also a source of many runtime disasters, either the double delete (also called a premature free from the old malloc/free routines), or the opposite, a memory leak. Automatic memory management was one of Java’s selling points as a C/C++-similar language without the memory bug risk. Later C# made the same pitch to users.

    I suggest using the STL and thinking about the ownership semantics of your foo. Maybe the Test class should own it; maybe it should share it; maybe it should really have a weak reference. Can't tell from a program fragment. I can only say you should review modern ideas of memory management in C++ and adopt them.