智能指针是 C++11 引入的一个非常实用的特性,旨在自动管理动态分配的内存,避免内存泄漏和悬空指针问题。主要有三种类型的智能指针:std::unique_ptr
、std::shared_ptr
和 std::weak_ptr
。下面是对它们的详细介绍:
std::unique_ptr
特性:
std::unique_ptr
实例只能拥有一个对象的唯一所有权。unique_ptr
,但可以移动(使用移动构造函数或移动赋值运算符)。使用场景:适用于表示唯一的拥有关系,不需要共享所有权的情况。
示例:
#include #include void uniquePtrExample() { std::unique_ptr ptr1(new int(10)); // 创建 unique_ptr std::cout << *ptr1 << std::endl; // 使用指针 std::unique_ptr ptr2 = std::move(ptr1); // 转移所有权 // std::cout << *ptr1; // 错误:ptr1 已经不再拥有对象 }
std::shared_ptr
特性:
std::shared_ptr
实例可以指向同一个对象。shared_ptr
被销毁时,内存会自动释放。使用场景:适用于多个对象共享同一资源的情况。
示例:
#include #include void sharedPtrExample() { std::shared_ptr ptr1(new int(20)); // 创建 shared_ptr { std::shared_ptr ptr2 = ptr1; // ptr2 也指向同一个对象 std::cout << *ptr2 << std::endl; // 输出 20 } // ptr2 离开作用域后,引用计数减少 std::cout << *ptr1 << std::endl; // 仍然有效输出 20 }
std::weak_ptr
特性:
shared_ptr
指向对象的非拥有性引用。使用场景:用于防止循环引用,或者在需要检查资源是否仍然有效时。
示例:
#include #include void weakPtrExample() { std::shared_ptr sptr(new int(30)); std::weak_ptr wptr = sptr; // 创建 weak_ptr if (auto sptr2 = wptr.lock()) { // 检查 weak_ptr 是否有效 std::cout << *sptr2 << std::endl; // 输出 30 } sptr.reset(); // 删除 sptr 指向的对象 if (auto sptr2 = wptr.lock()) { std::cout << *sptr2 << std::endl; // 输出为空,指向的对象已被释放 } else { std::cout << "资源已被释放" << std::endl; } }
利用智能指针可以帮助我们有效管理内存,降低内存泄漏的风险,提高程序的安全性和稳定性。🎉 选择合适的智能指针类型可以使代码更简洁和易于维护。