Does list.clear() delete the objects in the list? If not, what is the correct method?

M

Michael Jasn

I had a question about memory management. Please look at the two
functions below. Can you answer the two questions in the comments
below. Thanks so much.

-Mike


func1(std::vector<Point>& points)
{
points.clear(); // Is this the right way to deallocate
// memory allocated below? If not, how
// do I delete the object allocated below

...
points.push_back(Point(1,2)); //The Point object will on the heap
right?
...
}


func2()
{
vector<Point> points;

while(some condition)
{
..
func1(points);
..
}
}



Point::point(const float& new_x, const float& new_y)
:x(new_x),
y(new_y)
{}
 
J

John Harrison

Michael Jasn said:
I had a question about memory management. Please look at the two
functions below. Can you answer the two questions in the comments
below. Thanks so much.

-Mike


func1(std::vector<Point>& points)
{
points.clear(); // Is this the right way to deallocate
// memory allocated below? If not, how
// do I delete the object allocated below

There is no memory allocated below. The method clear() will resize the
vector to zero. Whether this involves deallocating any memory is
implementation defined.
...
points.push_back(Point(1,2)); //The Point object will on the heap
right?

No, the Point object will be in the vector. It will be a copy of the Point
object passed to push_back. This operation may or may not require memory
allocation but this isn't your concern, only vector needs to know this.

The important point is that you have no memory leak, any memory allocated by
vector will be freed eventually. If you want to resize a vector to zero and
free any memory that it is holding then there is no guaranteed way to do
that, but the following trick is reasonably sure to work

vector<Point>().swap(points);

This creates a vector using the default constructor and swaps it with
points. If the default constructor allocates no memory (which is a
reasonable assumption) then after this operation points will be a zero size
vector with no memory allocated.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top