智能指针是一种 C++ 中的抽象数据类型,它模拟普通指针的行为,同时还具有自动内存管理的功能。智能指针可以在对象不再需要时自动释放其所指向的内存,从而避免内存泄漏和悬空指针的问题。
智能指针通常会跟踪引用计数,以确定何时可以释放其所指向的对象。当一个智能指针被拷贝或赋值给其他智能指针时,引用计数会增加;当一个智能指针超出作用域或被显式释放时,引用计数会减少。当引用计数归零时,智能指针会自动释放其所管理的内存。
在 C++ 中,智能指针的实现通常基于模板类,其中包含了重载的解引用运算符和成员访问运算符,使得智能指针可以像普通指针一样进行操作。常见的智能指针包括 std::unique_ptr、std::shared_ptr 和 std::weak_ptr 等。
总的来说,智能指针是一种能够提供自动内存管理功能的指针,它大大简化了程序员对内存资源的管理,降低了内存泄漏和悬空指针的风险。
#include <iostream>
using namespace std;
template <class T>
class SmartPointer {
private:
T* ptr; // 原始指针
int* count; // 引用计数
public:
// 构造函数
explicit SmartPointer(T* p = nullptr) : ptr(p), count(new int(1)) {}
// 拷贝构造函数:增加引用计数
SmartPointer(const SmartPointer<T>& sp) : ptr(sp.ptr), count(sp.count) {
(*count)++;
}
// 赋值运算符重载:增加引用计数,并减少旧指针的引用计数
SmartPointer<T>& operator=(const SmartPointer<T>& sp) {
if (this != &sp) {
// 先增加新指针的引用计数
(*sp.count)++;
// 然后减少旧指针的引用计数
if (--(*count) == 0) {
delete ptr;
delete count;
}
// 更新指针和引用计数
ptr = sp.ptr;
count = sp.count;
}
return *this;
}
// 解引用运算符重载
T& operator*() const {
return *ptr;
}
// 成员访问运算符重载
T* operator->() const {
return ptr;
}
// 析构函数:减少引用计数,删除指针和引用计数对象
~SmartPointer() {
if (--(*count) == 0) {
delete ptr;
delete count;
}
}
};
int main() {
SmartPointer<int> sp1(new int(5));
SmartPointer<int> sp2 = sp1;
SmartPointer<int> sp3(new int(10));
sp2 = sp3;
cout << *sp2 << endl; // 输出 10
getchar();
return 0;
}