flyonok

统计

留言簿(8)

ACE

book

boost

bsd

c study

c++

code download

codeblock

computer clound

Eclipse

embed system

erlang

ET++

gtk

ic card

java

KDE

libevent

linux

linux--MM

mysql

network education

one card

oracle

pcap relation

php

powerbuilder

python

QT

software config

software test

SQL server

UML

wireless

wxwidgets

陈宾

阅读排行榜

评论排行榜

用在STL中的引用类指针

// cont/countptr.hpp

   #ifndef COUNTED_PTR_HPP
   #define COUNTED_PTR_HPP

   /*class for counted reference semantics
    *-deletes the object to which it refers when the last CountedPtr
    * that refers to it is destroyed
    */
   template <class T>
   class CountedPtr {
     private:
       T* ptr;        // pointer to the value
       long* count;   // shared number of owners

     public:
       //initialize pointer with existing pointer
       //-requires that the pointer p is a return value of new
       explicit CountedPtr (T* p=0)
        : ptr(p), count(new long(1)) {
       }

       //copy pointer (one more owner)
       CountedPtr (const CountedPtr<T>& p) throw()
        : ptr(p.ptr), count(p.count) {
           ++*count;
       }

       //destructor (delete value if this was the last owner)
       ~CountedPtr () throw() {
           dispose();
       }

       //assignment (unshare old and share new value)
       CountedPtr<T>& operator= (const CountedPtr<T>& p) throw() {
           if (this != &p) {
               dispose();
               ptr = p.ptr;
               count = p.count;
               ++*count;
           }
           return *this;
       }

       //access the value to which the pointer refers
       T& operator*() const throw() {
           return *ptr;
       }
       T* operator->() const throw() {
           return ptr;
       }

     private:
       void dispose() {
           if (--*count == 0) {
                delete count;
                delete ptr;
           }
       }
   };

   #endif /*COUNTED_PTR_HPP*/

posted on 2007-12-14 12:00 flyonok 阅读(436) 评论(1)  编辑 收藏 引用 所属分类: program

评论

# re: 用在STL中的引用类指针 2007-12-18 12:34 秦歌

顶一下  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理