本作业主要考察:复制控制/动态内存管理/模板编程/基于引用计数的智能指针原理/测试驱动开发
实现代码完成下面的my_shared_ptr以及main函数中的测试用例
本实现主要是利用复制控制来增加引用计数实现智能指针。
#include <iostream>
#include <vector>
using namespace std;template<class T>
class my_shared_ptr
{
public:my_shared_ptr();my_shared_ptr(T*);my_shared_ptr(const my_shared_ptr& from);~my_shared_ptr();my_shared_ptr& operator=(const my_shared_ptr& from);T* get(void);T& operator*(void);T* operator->(void);
private:void decrease(void);void copy(const my_shared_ptr& from);class share_count{public:share_count(void):m_count(1){}void add_count(void) { ++m_count; }void decrease_count(void) { --m_count; }long count(void) const { return m_count; }bool have_to_delete(void) const { return m_count == 0; }private:long m_count;};private:T* m_ptr;share_count* m_share_count;
};
template<class T>
my_shared_ptr<T>::my_shared_ptr():m_share_count(new share_count), m_ptr(nullptr)
{
}template<class T>
my_shared_ptr<T>::my_shared_ptr(T* t): m_share_count(new share_count), m_ptr(t)
{
}template<class T>
my_shared_ptr<T>::my_shared_ptr(const my_shared_ptr & from)
{copy(from);
}template<class T>
my_shared_ptr<T>::~my_shared_ptr()
{decrease();
}template<class T>
my_shared_ptr<T>& my_shared_ptr<T>::operator=(const my_shared_ptr& from)
{if (&from == this){return *this;}else{decrease();copy(from);}
}template<class T>
T* my_shared_ptr<T>::get(void)
{return m_ptr;
}template<class T>
T & my_shared_ptr<T>::operator*(void)
{if (m_ptr){return *m_ptr;}else{throw "operator* return *nullptr";}
}template<class T>
T * my_shared_ptr<T>::operator->(void)
{if (m_ptr){return m_ptr;}else{return nullptr;}
}template<class T>
void my_shared_ptr<T>::decrease(void)
{if (m_share_count->count() > 0){m_share_count->decrease_count();}if (m_share_count->have_to_delete()){if (m_ptr != nullptr){delete m_ptr;m_ptr = nullptr;}delete m_share_count;m_share_count = nullptr;}
}template<class T>
void my_shared_ptr<T>::copy(const my_shared_ptr & from)
{m_share_count = from.m_share_count;m_share_count->add_count();m_ptr = from.m_ptr;
}class A
{
public:A();~A();void Print(void) { std::cout << "I am an A objcet." << std::endl; }void PrintData(void) { std::cout << "I am an A objcet. My data is " << m_data << std::endl; }void SetData(int data);
private:int m_data = 100;
};
A::A()
{std::cout << "A::A()" << std::endl;
}
A::~A()
{std::cout << "A::~A()" << std::endl;
}
void A::SetData(int data)
{this->m_data = data;
}void test_nullptr(void)
{//指向空指针的场景my_shared_ptr<A> p;auto p1 = p;auto p2(p);
}void test_A(void)
{//指向动态对象的场景my_shared_ptr<A> p(new A);auto p1 = p;auto p2(p);
}my_shared_ptr<A> test_create(void)
{my_shared_ptr<A> p(new A);return p;
}std::vector<my_shared_ptr<A>> test_STL(void)
{std::vector<my_shared_ptr<A>> listA;for (int i = 0; i < 2; ++i){listA.push_back(my_shared_ptr<A>(new A));}return std::move(listA);
}int main(int argv, char* argc[])
{test_nullptr();test_A();auto p = test_create();p->PrintData();auto listA = test_STL();auto p1 = p;p->Print();p1->Print();(*p).Print();return 0;
}
输出如下: