Home >Backend Development >C++ >How to Avoid Memory Leaks with Vectors of Pointers in C ?
When working with dynamic memory allocation, it's crucial to prevent memory leaks. One common scenario involves using a vector of pointers to objects derived from a base class.
std::vector manages the memory for the pointers, but not the objects themselves. This means objects allocated through the vector's push_back() method will not be automatically deleted when the vector goes out of scope.
1. Manual Object Deletion:
This approach requires manually deleting each object before the vector goes out of scope, as demonstrated in the code below:
#include <vector> struct base { virtual ~base() {} }; struct derived : base {}; typedef std::vector<base*> container; void foo() { container c; for (unsigned i = 0; i < 100; ++i) c.push_back(new derived()); // Manual object deletion for (auto& obj : c) delete obj; }
2. Smart Pointers:
An alternative is using smart pointers, which provide automatic memory management. std::unique_ptr and std::shared_ptr are commonly used smart pointers:
std::unique_ptr:
A unique_ptr represents sole ownership of a resource. It automatically deletes the object when it goes out of scope.
#include <vector> #include <memory> struct base { virtual ~base() {} }; struct derived : base {}; typedef std::vector<std::unique_ptr<base>> container; void foo() { container c; for (unsigned i = 0; i < 100; ++i) c.push_back(std::make_unique<derived>()); }
std::shared_ptr:
A shared_ptr allows multiple owners to share a resource. It keeps track of the number of owners and deletes the object when the reference count reaches zero.
#include <vector> #include <memory> struct base { virtual ~base() {} }; struct derived : base {}; typedef std::vector<std::shared_ptr<base>> container; void foo() { container c; for (unsigned i = 0; i < 100; ++i) c.push_back(std::make_shared<derived>()); }
3. Boost::ptr_container:
Boost::ptr_container::ptr_vector is a specialized container designed to hold pointers and automatically delete them upon destruction:
#include <boost/ptr_container/ptr_vector.hpp> struct base { virtual ~base() {} }; struct derived : base {}; typedef boost::ptr_vector<base> container; void foo() { container c; for (int i = 0; i < 100; ++i) c.push_back(new Derived()); }
Remember, it's generally recommended to use smart pointers (especially std::unique_ptr) as they provide automatic, exception-safe memory management. Avoid manual object deletion and ensure that resources are always deallocated when no longer needed to prevent memory leaks and unpredictable behavior in your code.
The above is the detailed content of How to Avoid Memory Leaks with Vectors of Pointers in C ?. For more information, please follow other related articles on the PHP Chinese website!