What should i avoid to write memory-safe code using STL?

I used STL for quite some time, but mainly for implementing algorithms for its sake, except for a random vector in another code.

Before I start using it more, I would like to know what common mistakes people make when using STL - in particular, are there some things I should observe when using STL templates to protect my code from memory leaks?

+4
source share
3 answers

There are many bottlenecks in the use of STL, if you want to know more, I propose the book "Effective STL" by S. Meyers .

+12
source

When you store raw pointers to dynamically allocated objects in containers, containers will not manage their memory.

vector<FooBar*> vec; vec.push_back(new FooBar); //your responsibility to free them 

To make it more secure for data storage, use smart pointer containers or special-purpose pointer containers, as in Boost: pointer containers

In particular, given that if an exception is thrown, execution may not reach the manual cleanup code (unless painful efforts are made).

+9
source

in particular, are there any things that I should observe when using STL templates to protect my code from memory leaks?

STL or not, the answer is the same:

+6
source

Source: https://habr.com/ru/post/1340352/


All Articles