Smart pointers are tools in C that solve memory management problems by automatically managing memory release. Commonly used smart pointer types are: unique_ptr: exclusive ownership, releasing the pointed object when destroyed. shared_ptr: Shared ownership, reference counting tracks the number of pointers, and the object is released when the last pointer is destroyed. weak_ptr: Weak reference does not increase the object life cycle and can only be used in combination with shared_ptr.
C Smart pointers: The evolution of pointers, a good medicine to solve memory problems
Smart pointers are powerful tools in C. Help solve problems such as memory leaks and wild pointers by automatically managing memory release. Compared with traditional pointers, smart pointers are safer and more efficient, allowing programmers to focus on writing business logic without worrying about the tedious details of memory management.
unique_ptr
shared_ptr
weak_ptr
Suppose we have a Person
class, which represents a person. Our goal is to create a vector that stores Person
objects and ensure that the memory is automatically released when the vector goes out of scope.
#include <iostream> #include <vector> #include <memory> class Person { public: Person(const std::string& name) : name(name) {} ~Person() { std::cout << "Destructor called for " << name << std::endl; } private: std::string name; }; int main() { std::vector<std::shared_ptr<Person>> people; // 添加几个 Person 对象 people.push_back(std::make_shared<Person>("John")); people.push_back(std::make_shared<Person>("Mary")); people.push_back(std::make_shared<Person>("Bob")); // 遍历并打印名称 for (const auto& person : people) { std::cout << person->name << std::endl; } return 0; }
Output:
John Mary Bob Destructor called for John Destructor called for Mary Destructor called for Bob
In the example, we use std::shared_ptr<Person>
to store a pointer to the Person
object. When the people
vector is destroyed out of scope, the smart pointer will also be destroyed. This will automatically release the memory occupied by the Person
object and prevent memory leaks.
The above is the detailed content of C++ smart pointers: The evolution of pointers, a good solution to memory problems. For more information, please follow other related articles on the PHP Chinese website!