C++智能指针的设计和实现

Gloria ·
更新时间:2024-09-20
· 680 次阅读

  一、智能指针   在C++语言编程时,当类中有指针成员时,一般有两种方式来管理指针成员:一是采用值型的方式管理,每个类对象都保留一份指针指向的对象的拷贝;另一种更优雅的方式是使用智能指针,从而实现指针指向的对象的共享。   智能指针(smartpointer)的一种通用实现技术是使用引用计数(referencecount)。智能指针类将一个计数器与类指向的对象相关联,引用计数跟踪该类有多少个对象共享同一指针。   每次创建类的新对象时,初始化指针并将引用计数置为1;当对象作为另一对象的副本而创建时,拷贝构造函数拷贝指针并增加与之相应的引用计数;对一个对象进行赋值时,赋值操作符减少左操作数所指对象的引用计数(如果引用计数为减至0,则删除对象),并增加右操作数所指对象的引用计数;调用析构函数时,析构函数减少引用计数(如果引用计数减至0,则删除基础对象)。   智能指针详解:   包括:std::auto_ptr、boost::scoped_ptr、boost::shared_ptr、boost::scoped_array、boost::shared_array、boost::weak_ptr、boost::intrusive_ptr   二、智能指针的一般实现   智能指针通常使用类模板来实现。模拟类指针的各种行为。但是,其重要的作用是对类指针成员的管理,防止悬垂指针的出现。 template<classT> classSmartPointer{ public: SmartPointer(T*t):pt(t){} T&operator*(){return*pt;} T*operator->(){returnpt;} private: T*pt; };   三、引用计数的实现   为了实现引用计数,我们定义一个_counter类来记录引用次数,把_counter类的所有成员设定为private,因为其他的类型并不需要访问_counter,只有SmartPointer对其进行操作行了,SmartPointer将设为其友元类。 class_counter{ template<classT>friendclassSmartPointer; _counter(intu):use(u){} ~_counter(){} intuse; };

  在SmartPointer类中,保留_counter的指针。 template<classT> classSmartPointer{ public: SmartPointer(T*t):pc(new_counter(1)){ cout<<"SmartPointer::SmartPointer()invodeduseis:"<<pc->use<<endl; this->pt=t; } SmartPointer(SmartPointer<T>&rhs){ this->pc=rhs.pc; this->pt=rhs.pt; this->pc->use++; cout<<"SmartPointercopyinvokeduseis:"<<pc->use<<endl; } ~SmartPointer(){ pc->use--; cout<<"SmartPointer::~SmartPointer()invodeduseis:"<<pc->use<<endl; if(pc->use==0) { deletept; deletepc; } } SmartPointer<T>&operator=(SmartPointer<T>rhs){ if(rhs==*this){ return*this; } this->pt=rhs.pt; this->pc=rhs.pc; this->pc->use++; cout<<"SmartPointer::operator=()invokeduseis:"<<pc->use<<endl; return*this; } private: T*pt; _counter*pc; };   例如:我们有一个HasPtr类,其类成员中有一个为指针*p。 classHasPtr{ public: HasPtr(intval):value(val),p(newint(3)){ cout<<"HasPtr::HasPtr()invoked"<<endl; } ~HasPtr(){deletep;cout<<"HasPtr::~HasPtr()invoded"<<endl;} private: int*p; intvalue; };   如果如下调用:   HasPtr*php=newHasPtr(3);   SmartPointer<HasPtr>psp(php);   SmartPointer<HasPtr>npsp(psp);   我们现在有两个智能指针对象,指向同一个HasPtr对象,其模型如下:

  _counter的use成员(引用计数)为2.

  四、测试 intmain(void) { HasPtr*php=newHasPtr(3); SmartPointer<HasPtr>psp(php); SmartPointer<HasPtr>npsp(psp); SmartPointer<HasPtr>nnpsp=npsp; return0; }   使用gcc编译器,运行结果如下:



C++ 指针 c+ 智能指针

需要 登录 后方可回复, 如果你还没有账号请 注册新账号