C++11引入了智能指针(Smart Pointers)的概念,它们是一种自动管理内存的生命周期的指针类型,帮助开发者避免内存泄漏和野指针等问题。C++11标准库中定义了三种智能指针:std::unique_ptr、std::shared_ptr和std::weak_ptr。
原理
- std::unique_ptr:独占所有权模型,同一时间只能有一个unique_ptr指向某个对象,当unique_ptr被销毁(例如离开作用域)时,它所指向的对象也会被自动删除。
- std::shared_ptr:共享所有权模型,多个shared_ptr可以指向同一个对象,对象的生命周期会持续到最后一个拥有它的shared_ptr被销毁。当最后一个shared_ptr被销毁时,对象会被自动删除。shared_ptr使用引用计数(reference counting)来实现。
- std::weak_ptr:弱引用模型,weak_ptr是对对象的一种弱引用,它不会增加对象的引用计数。它主要用于解决shared_ptr之间的循环引用问题。
使用案例
std::unique_ptr
#include <memory>
class MyClass {
public:
MyClass() {
std::cout << "MyClass created\n"; }
~MyClass() {
std::cout << "MyClass destroyed\n"; }
};
int main()