How to use smart pointers in C++?
Using smart pointers in C++ is aimed at managing dynamically allocated memory to avoid memory leaks and dangling pointer issues. C++11 introduced two types of smart pointers: std::shared_ptr and std::unique_ptr, each with their own usage.
- shared_ptr: Multiple shared_ptr can point to the same object, and it will maintain a reference count. When the reference count reaches 0, the object will be automatically destroyed.
#include <memory>
int main() {
std::shared_ptr<int> ptr1 = std::make_shared<int>(10);
std::shared_ptr<int> ptr2 = ptr1;
// 使用智能指针访问对象
std::cout << *ptr1 << std::endl;
std::cout << *ptr2 << std::endl;
}
- unique_ptr has exclusive ownership, meaning it does not allow multiple unique_ptrs to point to the same object, and when the unique_ptr is destroyed, the object is also destroyed.
#include <memory>
int main() {
std::unique_ptr<int> ptr1 = std::make_unique<int>(10);
//std::unique_ptr<int> ptr2 = ptr1; // 编译错误,unique_ptr不支持拷贝
// 使用智能指针访问对象
std::cout << *ptr1 << std::endl;
}
In addition to shared_ptr and unique_ptr, C++11 also introduced weak_ptr to address the issue of circular references in shared_ptr. Utilizing smart pointers can greatly simplify memory management, enhancing code maintainability and security.