Allocating memory - Pointers

134 Views Asked by At

I want to know when or if I have to delete this object. Here is the constructor of a basic class Object Object.cpp:

Objects::Objects{
    Obj one = new Obj;
    Obj two = new Obj;
}

I know when allocating memory you are supposed to delete it at some point, but I have allocated memory in the constructor and want to use the variables one and two again. When do I delete them?

2

There are 2 best solutions below

2
eerorika On

I want to know when or if I have to delete this object.

If you allocate with new and don't deallocate, then you leak memory.

I have allocated memory in the constructor and want to use the variables one and two again, when do I delete them ?

If you want to initialise variables in constructor and use them later, then you should use non-static member variables instead of automatic variables in the constructor.

If you were to allocate memory in constructor, and point to it with a member, then typically you should deallocate in the destructor. For more information, see Resource Acquisition Is Initialisation idiom. However, you should not use bare owning pointers, and you should not use dynamic allocation unnecessarily. Here is a simple example that I recommend as your first option:

struct Objects {
    Obj objects[2];
};
2
Pat. ANDRIA On

To make it simple, anytime you make a new, you should make a corresponding delete.

In your case, you have to delete the allocated objects Obj at latest before your objects Objects are deleted, which means in the destructor of Objects, which also means that you have to keep a way to access to the one and two pointers at the destructor (one way might be to make them as a member of Objects). Your current case fails to do so because one and two are local variables and are not pointers.

It may look like the following:

class Objects
{
public:
  Objects();
  virtual ~Objects();
private:
  Obj* one;
  Obj* two;
};

Objects::Objects{
    one = new Obj;
    two = new Obj;
}

Objects::~Objects{
    delete one;
    delete two;
}

There are some rules you need to be aware of, when coping with resource management and it is the rule of three/five/zero which will guide you to create robust code in terms of resource management.

Another remark: It might be better to use smart pointers as even with the approach I mentionned in my post, if an exception or a crash happenned before your code executes the delete lines, you would still have a memory leak as explained here