最近在找工作,发现许多公司在面试的时候会要求手写智能指针,因此自己参照的别人的博客在上面修改了一些,作为参考原文连接。shared_ptr通过引用计数来管理多个指针指向同一个对象,对计数器的操作要格外重视。
#include<iostream>
using namespace std;
//自定义智能指针
template <class T> class SmartPointer {
public:
SmartPointer(T* ptr) {
ref = ptr;
ref_count = new unsigned;
*ref_count = 1;
}
//指针拷贝构造函数,新建一个指向已有对象的智能指针
SmartPointer(SmartPointer<T>& sptr) {
ref = sptr.ref;
ref_count = sptr.ref_count