std::shared_ptr
is a part of the C++11 standard and is used to manage resources and memory allocation. It helps in preventing memory leaks, provides a safer and more convenient way to perform memory management, and reduces the likelihood of dangling pointers.
Creating a std::shared_ptr
The std::shared_ptr
can be created using the std::make_shared
function or by using the constructor.
#include <memory>
int main() {
// Using make_shared
std::shared_ptr<int> ptr1 = std::make_shared<int>(5);
// Using constructor
std::shared_ptr<int> ptr2(new int(10));
return 0;
}
Accessing the Managed Object
You can access the managed object using the get()
method of std::shared_ptr
.
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> ptr(new int(15));
std::cout << *ptr.get() << std::endl; // Output: 15
return 0;
}
Sharing Ownership
std::shared_ptr
can be copied, and each copy maintains a reference count. When the last std::shared_ptr
owning the resource is destroyed or reset, the managed object is automatically deleted.
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> ptr1(new int(20));
std::shared_ptr<int> ptr2 = ptr1;
std::cout << *ptr1 << std::endl; // Output: 20
std::cout << *ptr2 << std::endl; // Output: 20
return 0;
}
Conclusion
std::shared_ptr
is a powerful tool for managing resources in C++. It provides automatic memory management, prevents memory leaks, and allows multiple pointers to share ownership of the same resource. It is a valuable addition to modern C++ programming.
References: