When do I really need to use Delete in Destructors?

if I do Point P = new Point();

I've been told every time I use new, it stays in memory even when out of scope and that I should use delete to remove it.. so do i need to do Delete P?

The thing is, shouldn't the destructor take care of it? Also when the program terminates, wouldn't it free?

also I have:

class PA				//array of P..
{
	private:
		vector<P> DataHolder;
	public:
		PA() {}
		PA(P) : DataHolder.push_back(P) {}
		PA(....)
		{
			//push back all values in the elipsis..
		}
		
		~PA()
		{
			//Do I need a delete in a for loop here?
		}
};

P.S. what is the difference between new [] and new.. and delete [] and delete? One is for arrays?

The memory is only "lost" while you are running the program. Once program is completed any "lost" memory is freed up by the operating system.

Yes you should use delete if you used new to create a member variable within an object. It may, or may not be appropriate to do that within the destructor, but that is a common place to do it.

Yes, [] relates to arrays when using new and delete.

so.. if I do:

int main()
{
  Point P = new Point();
  delete P;   //Needed? Or can I just put it in the destructor if it is even needed..
}

should I use Point P = new Point(); or just Point P = Point(0, 0);

delete p; invokes the destructor for pointers. Putting a call to delete in a destructor is only applicable if there is memory maintained within the object itself.

>> When do I really need to use Delete in Destructors?

When your class is responsible for allocating the memory that a pointer points to, then it is also responsible for deallocating that memory. This is what is referred to as ownership.

If your class creates a dynamic array, or a dynamically allocated object, or an array of dynamically allocated arrays or objects, in other words, if you use 'new' in your constructor, then you must use delete in the destructor to deallocate that memory.

You can save yourself all this trouble by making use of "scope-based resource management" (or RAII for "Resource Acquisition Is Initialization). Classes like std::vector and std::string are examples of array-like RAII classes, and classes like std::shared_ptr and std::unique_ptr are examples of RAII classes that wrap a pointer (i.e. otherwise called a "smart-pointer").


>> I've been told every time I use new, it stays in memory even when out of scope and that I should use delete to remove it.. so do i need to do Delete P?

Yes. new is an operator to do a manual allocation of memory. If you allocate memory manually, you must deallocate it manually, with delete . Whatever piece of code allocates the memory, that piece of code (class, function, module, etc.) is responsible for deleting it in due time. Smart-pointers can be used to attach some automatic deallocation behaviour to the pointer, so that you don't worry about it down the line.


>> The thing is, shouldn't the destructor take care of it?

No, because there are other things you could do with a pointer. Your pointer could be a pointer to something else that is not owned by your object, it might point nowhere, it might point to a foreign object (so-called "opaque pointer"), it might point to some position in an array (like for a ring-buffer), etc. etc. The compiler cannot assume that because you have a pointer as a data member that it automatically requires a delete in the destructor, even if a new or new[] appears in the constructor.


>> Also when the program terminates, wouldn't it free?

Yes, it will be freed when the program terminates, we usually say that "the memory is re-claimed by the operating system". So, you might ask, why do we care about this memory leak? For a few reasons. First, you are using more memory, during execution, than you actually need, and that might be a problem on some platforms or for some memory-hungry programs. Second, if you happen to run a piece of memory leaking code in a loop (especially a infinite-loop), then your program will eventually eat up all your system memory until your computer crashes. Finally, if you produce code with lots of memory leaks, you are likely to get a pretty bad reputation as a programmer (its a good metric for programming competence, especially in C++).


>> //Do I need a delete in a for loop here?

No. Your class receives a bunch of pointers through its constructor. The objects that those pointers (stored in the vector) actually point to were not created by your class, thus, your class is not responsible for destroying them. It's the responsibility of the allocator to do the deallocation. Whoever created those pointers is responsible for destroying them. I do recommend you read my tutorials on RAII and ownership.

>> P.S. what is the difference between new [] and new.. and delete [] and delete? One is for arrays?

The new is for allocating a single object, the new[] is for allocating an array of objects. Anything that was allocated with new must be deleted with delete , and anything that was allocated with new[] must be deleted with delete[] . As simple as that.


>> should I use Point P = new Point(); or just Point P = Point(0, 0);

In this case, you should just use Point P = Point(0, 0); . There is no point in creating a single local variable with new . Overall, in C++, there is a strong preference in favour of using value-semantics and scope-based local variables (automatic variables). This causes some head-aches when doing more "pure" object-oriented programming, where reference-semantics and memory management seems to be easier, but that's where smart-pointers come to the rescue. Other than that little issue for doing OOP, value-semantics and scope-based, automatic storage is vastly more convenient and it is certainly preferred to use that as much as possible in C++ (in fact, if you use smart-pointers, references, and RAII containers, then you end up doing nothing but that).

commented: AGAIN! Thank you and Lerner Both exactly what I wanted to know! +6

Point P = new Point(); //delares a single new Point on the heap.
delete P; //is appropriate.

Point * points = new Point[10]; //declares and array of 10 Points
delete points[]; //deletes the memory allocated for points by new.

struct Polyhedron
{
  Polyhedron();
  Point * points;
  void declareNumberOfVertexes(int x)
  {
    points = new Point[x];
  }
  ~Polyhedron() {delete points[];}
};

Declares user defined class that can have unknown number of Points at declaration of object. User can decide number of vertexes(each Point object is a vertex) each Polyhedron object will have. The destructor releases the memory allocated for each Polyhedron object.

commented: That is one epic example!! +6

Was confused about putting it in the destructor but not anymore! I'm going to mark this as solved. Everything I ever wanted to know and was going to ask and more has been answered by the two above.

Thank you guys! Rep+ for both.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.