Smart Pointers in C++
Smart pointers in C++ are objects that manage the memory of dynamically allocated objects. They automatically delete the memory when it is no longer needed, which helps prevent memory leaks and other memory-related bugs. Here's an example of using smart pointers in C++:
c++
#include <iostream>
#include <memory>
class Person {
public:
std::string name;
Person(std::string name) {
this->name = name;
std::cout << "Creating Person object: " << name << std::endl;
}
~Person() {
std::cout << "Destroying Person object: " << name << std::endl;
}
};
int main() {
std::shared_ptr<Person> person1 = std::make_shared<Person>("John");
std::shared_ptr<Person> person2 = std::make_shared<Person>("Jane");
person2 = person1;
std::cout << "Person 1 name: " << person1->name << std::endl;
std::cout << "Person 2 name: " << person2->name << std::endl;
return 0;
}
In this example, we're using the std::shared_ptr class to create two smart pointers to Person objects. We're using the std::make_shared function to create the objects, which automatically allocates memory and creates the objects. We're then assigning person1 to person2, which causes the reference count of the Person object to increase to 2. When person2 is reassigned, the reference count of the original Person object is decreased to 1. When the program exits, the memory for the Person object is automatically deallocated by the smart pointer, even though we didn't explicitly call delete.
No comments:
Post a Comment