I've used STL for quite a while now, but mostly to implement algorithms for the sake of it, other than the occasional vector in other code.
Before I start using it more, I wanted to know what the common mistakes people make when using STL are -- in particular, are there any things I should watch for when using STL templates to keep my code safe from memory leaks?
To avoid memory leaks, memory allocated on heap should always be freed when no longer needed.
The best way to avoid memory leaks in C++ is to have as few new/delete calls at the program level as possible – ideally NONE. Anything that requires dynamic memory should be buried inside an RAII object that releases the memory when it goes out of scope.
Holding the references of the object and resources that are no longer needed is the main cause of the memory leaks in android applications. As it is known that the memory for the particular object is allocated within the heap and the object point to certain resources using some object reference.
The memory leak would occur if the floor number requested is the same floor that the elevator is on; the condition for releasing the memory would be skipped. Each time this case occurs, more memory is leaked. Cases like this would not usually have any immediate effects.
There are a lot of bottlenecks in using STL effectively, if you want to know more I'd suggest the book "Effective STL" by S.Meyers.
When you store raw pointers to dynamically allocated objects in containers, containers won't manage their memory.
vector<FooBar*> vec;
vec.push_back(new FooBar); //your responsibility to free them
To make it more memory-leak proof use containers of smart pointers, or special-purpose pointer containers, as in Boost: pointer containers
Particularly considering that if an exception gets thrown, execution might not reach the manual clean-up code (unless painful efforts are made).
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