Coming from a C# background, I have only vaguest idea on memory management on C++-- all I know is that I would have to free the memory manually. As a result my C++ code is written in such a way that objects of the type std::vector
, std::list
, std::map
are freely instantiated, used, but not freed.
I didn't realize this point until I am almost done with my programs, now my code is consisted of the following kinds of patterns:
struct Point_2
{
double x;
double y;
};
struct Point_3
{
double x;
double y;
double z;
};
list<list<Point_2>> Computation::ComputationJob
(list<Point_3>pts3D, vector<Point_2>vectors)
{
map<Point_2, double> pt2DMap=ConstructPointMap(pts3D);
vector<Point_2> vectorList = ConstructVectors(vectors);
list<list<Point_2>> faceList2D=ConstructPoints(vectorList , pt2DMap);
return faceList2D;
}
My question is, must I free every.single.one of the list usage ( in the above example, this means that I would have to free pt2DMap
, vectorList
and faceList2D
)? That would be very tedious! I might just as well rewrite my Computation
class so that it is less prone to memory leak.
Any idea how to fix this?
No, memory are not freed. In C++11, you can use the shrink_to_fit method for force the vector to free memory. You can use it, but the standard specifies that it does not force extra memory to be released (§23.3. 6.3/6): "shrink_to_fit is a non-binding request to reduce capacity() to size()."
So there is no surprise regarding std::vector. It uses 4 bytes to store each 4 byte elements. It is very efficient.
Vectors are assigned memory in blocks of contiguous locations. When the memory allocated for the vector falls short of storing new elements, a new memory block is allocated to vector and all elements are copied from the old location to the new location. This reallocation of elements helps vectors to grow when required.
No: if objects are not allocated with new
, they need not be freed/deleted explicitly. When they go out of scope, they are deallocated automatically. When that happens, the destructor is called, which should deallocate all objects that they refer to. (This is called Resource Acquisition Is Initialization, or RAII, and standard classes such as std::list
and std::vector
follow this pattern.)
If you do use new
, then you should either use a smart pointer (scoped_ptr
) or explicitly call delete
. The best place to call delete
is in a destructor (for reasons of exception safety), though smart pointers should be preferred whenever possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With