67 lines
1.3 KiB
C
67 lines
1.3 KiB
C
|
#pragma once
|
||
|
|
||
|
#include "../ex_object.h"
|
||
|
|
||
|
// 基本
|
||
|
void base();
|
||
|
|
||
|
// 自定义一个简单的智能指针
|
||
|
template <typename T>
|
||
|
class MSmartPointer {
|
||
|
private:
|
||
|
T* ptr;
|
||
|
size_t* refCount;
|
||
|
|
||
|
public:
|
||
|
MSmartPointer() : ptr(nullptr), refCount(nullptr) {}
|
||
|
|
||
|
explicit MSmartPointer(T* p) : ptr(p), refCount(new size_t(1)) {}
|
||
|
|
||
|
// 拷贝构造函数
|
||
|
MSmartPointer(const MSmartPointer& other)
|
||
|
: ptr(other.ptr), refCount(other.refCount)
|
||
|
{
|
||
|
if (!refCount) {
|
||
|
return;
|
||
|
}
|
||
|
++(*refCount);
|
||
|
}
|
||
|
|
||
|
// 析构函数
|
||
|
~MSmartPointer()
|
||
|
{
|
||
|
if (refCount && --(*refCount) <= 0) {
|
||
|
delete ptr;
|
||
|
delete refCount;
|
||
|
ptr = nullptr;
|
||
|
refCount = nullptr;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// 重载赋值操作符
|
||
|
MSmartPointer& operator=(const MSmartPointer& other)
|
||
|
{
|
||
|
if (this == &other) {
|
||
|
return *this;
|
||
|
}
|
||
|
|
||
|
if (refCount && --(*refCount) <= 0) {
|
||
|
delete ptr;
|
||
|
delete refCount;
|
||
|
}
|
||
|
|
||
|
ptr = other.ptr;
|
||
|
refCount = other.refCount;
|
||
|
|
||
|
if (refCount) {
|
||
|
++(*refCount);
|
||
|
}
|
||
|
return *this;
|
||
|
}
|
||
|
|
||
|
T& operator*() const { return *ptr; }
|
||
|
T* operator->() const { return ptr; }
|
||
|
};
|
||
|
|
||
|
// 测试用例
|
||
|
void test_example();
|