Shared_ptr.h
#pragma once
template <typename T>
class Shared_ptr {
public:
Shared_ptr();
Shared_ptr(T *p);
Shared_ptr(const Shared_ptr &sp);
Shared_ptr &operator=(const Shared_ptr &sp);
T &operator*();
T &operator*() const;
~Shared_ptr();
private:
T *ptr;
unsigned *count;
};
template <typename T>
Shared_ptr<T>::Shared_ptr()
: ptr(nullptr), count(nullptr) {}
template <typename T>
Shared_ptr<T>::Shared_ptr(T *p)
: ptr(p), count(new unsigned(1)) {}
template <typename T>
Shared_ptr<T>::Shared_ptr(const Shared_ptr<T> &sp)
: ptr(sp.ptr), count(sp.count) {
++*count;
}
template <typename T>
Shared_ptr<T> &Shared_ptr<T>::operator=(const Shared_ptr &sp) {
--*count;
if (0 == count) {
delete ptr;
delete count;
ptr = nullptr;
count = nullptr;
}
ptr = sp.ptr;
count = sp.count;
++*count;
return *this;
}
template <typename T>
T &Shared_ptr<T>::operator*() {
return *ptr;
}
template <typename T>
T &Shared_ptr<T>::operator*() const {
return *ptr;
}
template <typename T>
Shared_ptr<T>::~Shared_ptr() {
if (count && --*count == 0) {
delete ptr;
delete count;
ptr = nullptr;
count = nullptr;
}
}
Unique_ptr.h
#pragma once
template <typename T>
class Unique_ptr {
public:
Unique_ptr();
Unique_ptr(T *ptr);
Unique_ptr(const Unique_ptr &up) = delete;
~Unique_ptr();
Unique_ptr &operator=(const Unique_ptr &up) = delete;
T *release();
void reset(T *np);
T &operator*();
T &operator*() const;
private:
T *ptr;
};
template <typename T>
Unique_ptr<T>::Unique_ptr()
: ptr(nullptr) {}
template <typename T>
Unique_ptr<T>::Unique_ptr(T *ptr)
: ptr(ptr) {}
template <typename T>
T *Unique_ptr<T>::release() {
T *q = ptr;
ptr = nullptr;
return q;
}
template <typename T>
void Unique_ptr<T>::reset(T *np) {
if (ptr) {
delete ptr;
}
ptr = np;
}
template <typename T>
Unique_ptr<T>::~Unique_ptr() {
if (ptr) {
delete ptr;
}
}
template <typename T>
T &Unique_ptr<T>::operator*() {
return *ptr;
}
template <typename T>
T &Unique_ptr<T>::operator*() const {
return *ptr;
}
main.cpp
#include <iostream>
#include <string>
#include "shared_ptr.h"
#include "unique_ptr.h"
using namespace std;
struct obj {
obj(int n, string s)
: num(n), str(s) {}
int num = 0;
string str;
};
int main() {
auto p = new obj(1, "hello");
Shared_ptr<obj> o(p);
Shared_ptr<obj> t(o);
cout << (*t).num << endl;
cout << (*t).str << endl;
auto q = new obj(2, "apple");
Unique_ptr<obj> n(q);
cout << (*n).num << endl;
cout << (*n).str << endl;
auto w = new obj(3, "map");
n.reset(w);
cout << (*(n.release())).str << endl;
return 0;
}
析构函数的析构条件特别重要,是指向数据的指针不为NULL,并且共享指针的引用计数减1为0时,才析构数据。
未完成工作:添加删除器