#include <iostream>
using namespace std;
template <typename T>
class shared_ptr {
private:
// 引用计数指针与模板指针
int* count;
T* ptr;
public:
// 构造函数,初始化引用计算与模板指针
shared_ptr(T* p) : count(new int(1)), ptr(p) {
cout << "调用构造函数" << endl;
}
// 复制构造函数,引用计算+1
shared_ptr(shared_ptr<T>& other) : count(&(++*other.count)), ptr(other.ptr){
cout << "调用复制构造函数" << endl;
}
// 指针运算符
T* operator->() {
cout << "调用指针运算符" << endl;
return ptr; // 返回模板指针
}
// 解引用运算符
T& operator*() {
cout << "调用解引用运算符" << endl;
return *ptr; // 返回对象本身
}
// 赋值操作符重载
shared_ptr<T>& operator=(shared_ptr<T>& other) {
++*other.count;
if (this->ptr && --*this->count == 0) {
cout << "清理原智能指针" << endl;
delete count;
delete ptr;
}
cout << "调用赋值操作符" << endl;
this->ptr = other.ptr;
this->count = o
C++ sharedPtr实现
于 2022-03-06 23:37:44 首次发布
本文详细介绍了C++中一个简单的`shared_ptr`模板类的实现,包括构造函数、复制构造函数、指针和解引用运算符的重载,以及赋值操作符的实现。此外,还展示了如何在`main`函数中使用`shared_ptr`来管理内存,强调了智能指针在内存管理中的作用和引用计数的概念。

最低0.47元/天 解锁文章
3万+

被折叠的 条评论
为什么被折叠?



