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?
If you allocate with
newand don't deallocate, then you leak memory.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: