这部分是额外的代码的博客。键45条款想法已经实现。
#include<iostream>
using namespace std;
template<typename T>
class SharedPtr
{
public:
template<typename U>
SharedPtr(const SharedPtr<U>&u) :ptr(u.get())
{
count++;
}
SharedPtr(T*ptr_):ptr(ptr_){}
T*get()const{ return ptr; }
~SharedPtr()
{
if (1 == count)
{
count--;
delete ptr;
ptr = NULL;
}
}
private:
T* ptr;
int count;
};
class A{};
class B :public A{};
class C{};
int main()
{
SharedPtr<B> b1(new B());
SharedPtr<C> c1(new C());
SharedPtr<A> a1 = b1;
SharedPtr<A> a2 = c;//不能通过编译
return 0;
}