C++ vector memory release stepping on the pit

Table of contents

smart pointer

Vector moves the element position:


In C++, std::vectoris a self-managing container that automatically handles memory allocation and deallocation. When you std::vectoradd elements in it, it automatically allocates enough memory to store the elements. When std::vectordestroyed (for example, when it goes out of scope, or it is a member of an object and that object is destroyed), it automatically destroys all elements and frees the memory used to store the elements. Therefore, you usually don't need to worry std::vectorabout memory leaks.

However, if you std::vector're storing pointers in , and those pointers point to dynamically allocated memory, then you need to make sure that the memory is properly freed when it's no longer needed. std::vectordoes not automatically delete the memory pointed to by its elements, so you need to manually delete these memory, or use smart pointers (such as std::unique_ptror std::shared_ptr) to automatically manage this

Guess you like

Origin blog.csdn.net/jacke121/article/details/132374672