自定义数据类型
class stu {
private:
string m_name;
int m_age;
public:
stu(string name, int age) {
m_name = name;
m_age = age;
}
~stu() {}
void showInfo() {
cout <<"姓名:" << this->m_name<<"年龄:" << this->m_age << endl;
}
};
定义共享指针shared_ptr
template <typename T>
class mysharedPtr {
public:
mysharedPtr(T* ptr = nullptr) {
m_ptr = ptr;
m_count = new int(0);
++(*m_count);
}
~mysharedPtr() {
--(*m_count);
if ((*m_count) == 0) {
delete m_count;
m_count = nullptr;
delete m_ptr;
m_ptr = nullptr;
}
}
mysharedPtr(const mysharedPtr& other) {
m_ptr = other.m_ptr;
m_count = other.m_count;
++(*m_count);
}
mysharedPtr operator=(const mysharedPtr& other) {
++(*other.m_count);
--(*m_count);
if ((*m_count) == 0) {
delete m_count;
m_count = nullptr;
delete m_ptr;
m_ptr = nullptr;
}
m_count = other.m_count;
m_ptr = other.m_ptr;
return *this;
}
T* operator->() {
return m_ptr;
}
private:
T* m_ptr;
int* m_count;
};
主函数
#include<iostream>
#include<stdlib.h>
using namespace std;
int main() {
mysharedPtr<stu>ptr1 (new stu("zhangsan", 20));
ptr1->showInfo();
mysharedPtr<stu>ptr2(ptr1);
mysharedPtr<stu>ptr3 = ptr1;
ptr2->showInfo();
ptr3->showInfo();
}