I am writing a program using vector and am wondering if my destructor is correct, or do I need to add another line. The clear, clears all the elements in the vector, but do I need to add another line to delete the vector, and if I do what line should I add. I tried delete empID and varations of that and all I got was error messages.

heap::~heap(){
	empID.clear();
}

empID is the name of the vector and it is ints.

Recommended Answers

All 3 Replies

You don't need any of the code you've shown.

To elaborate a bit more. Your data member "empID" will have its destructor implicitly called when your object of class "heap" gets destroyed. And since std::vector will release all its memory in its destructor, there is nothing you need to do in your destructor (it is all done implicitly, that's the magic of RAII).

By opposition, if you have a dynamically allocated array that you hold with a pointer, then you would need the "delete[] ptr;" in your destructor because the destructor for pointer types does nothing to release the pointed-to memory (in fact the destructor for any primitive type is empty).

In that sense, STL containers are very safe when it comes to preventing memory leaks. In fact, if you use only RAII components, then the memory management coding-efforts are greatly reduced (and virtually all class-destructors turn out to be empty or omitted).

What mike_2000_17 said.

Also: The moment you allocate a resource in a constructor and use a pointer to keep track of it, you have just obligated yourself to do something about a copy constructor and copy-assignment operator. Because if you don't, then copying an object of your class will copy the pointer, and you will have two pointers pointing at the same resource.

Now when you destroy one of the copies of your object, its destructor will either free the resource, in which case destroying the other copy will try to free a resource that has already been freed, or it won't free the resource, which will result in a resource leak.

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.