代码展示
下面展示c++智能指针实现的代码
// An highlighted block
#include <iostream>
class RefBase{
private:
int count;
public:
RefBase():count(0){};
void incStrong(){ count++; };
void decStrong(){ count--; };
int getStrongCount(){ return count;};
};
class Person:public RefBase
{
public:
Person()
{
std::cout<<"Person()"<<std::endl;
}
~Person()
{
std::cout<<"~Person()"<<std::endl;
}
void print_inf(void)
{
std::cout<<"this is a test function!"<<std::endl;
}
};
template<typename T>
class sp{
private:
T *p;
public:
sp() : p(0) {}
sp( T* other )
{
std::cout<<"sp( Person* other )"<<std::endl;
p = other;
p->incStrong();
}
sp( const sp &other )
{
std::cout<<"p( const sp &other )"<<std::endl;
p = other.p;
p->incStrong();
}
~sp(){
if (p){
std::cout<<"~sp()"<<std::endl;
p->decStrong();
if (p->getStrongCount() == 0)
{
delete p ;
p = NULL;
}
}
}
T *operator->()
{
return p;
}
T& operator*()
{
return *p;
}
};
template<typename T>
void test( sp<T> &other )
{
sp<T> s = other;
std::cout<<"In test fuction"<<s->getStrongCount()<<std::endl;
s->print_inf();
}
void main()
{
//减少Person*指针;用sp替代person*
sp<Person> other = new Person();
std::cout<<"before test function"<<other->getStrongCount()<<std::endl;
test(other);
}