Vanwaril
Vanwaril

Reputation: 7518

What should be avoided to write memory-leak-safe code using STL?

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?

Upvotes: 5

Views: 424

Answers (3)

UncleBens
UncleBens

Reputation: 41333

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).

Upvotes: 9

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59101

in particular, are there any things I should watch for when using STL templates to keep my code safe from memory leaks?

STL or not, the answer is the same:

Upvotes: 6

grzkv
grzkv

Reputation: 2619

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.

Upvotes: 13

Related Questions