环境CLion + MinGW
//手动重写智能指针
#include "CustomPtr.h"
class Student {
public:
~Student() {
cout << "析构函数 释放Student" << endl;
}
};
// TODO 智能指针内置的
void action() {
Student *student1 = new Student();
Student *student2 = new Student();
// TODO 第一种情况
// shared_ptr<Student> sharedPtr1(student1);
// shared_ptr<Student> sharedPtr2(student2);
// TODO 第二种情况
shared_ptr<Student> sharedPtr1 (student1);
shared_ptr<Student> sharedPtr2 = sharedPtr1;
// TODO 打印
cout << "智能指针内置的 sharedPtr1:" << sharedPtr1.use_count() << endl;
cout << "智能指针内置的 sharedPtr2:" << sharedPtr2.use_count() << endl;
}
void action2() {
Student *student1 = new Student();
Student *student2 = new Student();
// TODO 第一种情况
// Ptr<Student> sharedPtr1(student1);
// Ptr<Student> sharedPtr2(student2);
// TODO 第二种情况 拷贝构造函数
// Ptr<Student> sharedPtr1 (student1);
// Ptr<Student> sharedPtr2 = sharedPtr1;
// TODO 第二种情况
// TODO 情况一
// Ptr<Student> sharedPtr1 (student1); // 调用手写智能指针的拷贝构造函数
// Ptr<Student> sharedPtr2;
// sharedPtr2 = sharedPtr1;
// TODO 情况二
Ptr<Student> sharedPtr1 (student1); //调用手写智能指针的=运算符重载函数
Ptr<Student> sharedPtr2 (student2);
sharedPtr2 = sharedPtr1;
// TODO 打印
cout << "手写的智能指针 sharedPtr1:" << sharedPtr1.use_count() << endl;
cout << "手写的智能指针 sharedPtr2:" << sharedPtr2.use_count() << endl;
}
int main(){
// cout << "下面是 C++内置智能指针 ===========" << endl;
// action();
// cout << endl;
cout << "下面是 自定义的智能指针 ===========" << endl;
action2();
return 0;
}
#ifndef TEST_CLION_CUSTOMPTR_H
#define TEST_CLION_CUSTOMPTR_H
#pragma once
#include <iostream>
#include <memory> // 智能指针的
using namespace std;
template<typename T>
class Ptr {
private:
T *object;
int *count;
public:
Ptr() { //空参构造方法,当new 一个空对象时执行
count = new int(1);
object = 0;
}
Ptr(T *t) : object(t) {//当new一个带有T的参数对象时执行
count = new int(1);
};
~Ptr() {
if (--(*count) == 0) {
if (object) {
delete object;
}
// 归零
delete count;
object = 0;
count = 0;
}
}
Ptr(const Ptr<T> &p) {
cout << "拷贝构造函数" << endl;
++(*p.count);
object = p.object; //当执行时左边是通过this拿到的新对象 右边是传进来的旧对象
count = p.count;
}
Ptr<T> &operator=(const Ptr<T> &p) {
cout << "=号运算符重载" << endl;
++(*p.count);
if (--(*count) == 0) { //场景: 对象2 = 对象1 操作:先对对象2进行析构 目前是清空对象2所有成员的指向,然后再进行赋值
if (object) { //否则对象2 赋值前属于野对象
delete object;
}
delete count;
}
object = p.object; //执行时左边是对象2(this 指向) 右边是传进来的对象1
count = p.count;
return *this; // 运算符重载的返回
}
//返回对象的引用个数
int use_count() {
return *this->count;
}
};
#endif //TEST_CLION_CUSTOMPTR_H