Assume I have defined a class like this:
class foo { private: std::vector< int* > v; public: ... void bar1() { for (int i = 0; i < 10; i++) { int *a = new int; v.push_back( a ); } }; void bar2() { std::vector< int >::iterator it = v.begin(); for ( ; it != v.end(); it++ ) std::cout << (*it); v.clear(); } };
In short, I push back some pointers in a vector, later I clear the vector. The question is, does this code has memory leak? I mean by clearing the vector, are the pointers deleted properly?
Yes, the code has a memory leak unless you delete the pointers. If the foo class owns the pointers, it is its responsibility to delete them. You should do this before clearing the vector, otherwise you lose the handle to the memory you need to de-allocate.
In short deleting a vector of pointers without creating any memory leaks. delete *it; tckts. erase(tckts.
The vector contains pointers. erase() will remove a pointer from the vector, but will not free the object that the pointer is pointing at. You have to free the object separately.
All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.
Yes, the code has a memory leak unless you delete the pointers. If the foo
class owns the pointers, it is its responsibility to delete them. You should do this before clearing the vector, otherwise you lose the handle to the memory you need to de-allocate.
for (auto p : v) { delete p; } v.clear();
You could avoid the memory management issue altogether by using a std::vector
of a suitable smart pointer.
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