Changeset 570

Show
Ignore:
Timestamp:
08/20/09 08:57:55 (15 years ago)
Author:
vbarta
Message:

supporting shared_ptr<const T>

Location:
library
Files:
2 modified

Legend:

Unmodified
Added
Removed
  • library/bdm/shared_ptr.h

    r565 r570  
    183183 
    184184        /*! 
     185          \brief const cast 
     186 
     187          Shared pointer to T can be converted to shared pointer to 
     188          const T, just like T * can be converted to T const *. 
     189        */ 
     190        template<typename U> 
     191        operator shared_ptr<const U>() const { 
     192                shared_ptr<const U> cptr;                
     193                cptr.refCnt = refCnt; 
     194                cptr.payload = payload; 
     195                add_ref(); 
     196                return cptr; 
     197        } 
     198 
     199        /*! 
    185200          \brief Efficient swap for shared_ptr. 
    186201         */ 
  • library/tests/shared_ptr_test.cpp

    r565 r570  
    2121 
    2222typedef std::vector<bdm::shared_ptr<Foo> > TFooVector; 
     23 
     24typedef std::vector<bdm::shared_ptr<const Foo> > TConstFooVector; 
    2325 
    2426TEST ( test_shared_ptr ) { 
     
    5355} 
    5456 
     57TEST ( test_shared_ptr_const ) { 
     58        TConstFooVector v; 
     59 
     60        bdm::shared_ptr<const Foo> zero; 
     61        CHECK_EQUAL ( 0l, zero.use_count() ); 
     62        bdm::shared_ptr<const Foo> z2 ( zero ); 
     63        CHECK_EQUAL ( 0l, z2.use_count() ); 
     64 
     65        bdm::shared_ptr<const Foo> one ( new Foo ( 1 ) ); 
     66        v.push_back ( one ); 
     67        CHECK ( !one.unique() ); 
     68 
     69        v.push_back ( one ); 
     70        v.push_back ( bdm::shared_ptr<const Foo> ( new Foo ( 2 ) ) ); 
     71        CHECK_EQUAL ( static_cast<TConstFooVector::size_type> ( 3 ), v.size() ); 
     72 
     73        CHECK ( v[0] == v[1] ); 
     74        CHECK ( v[1] != v[2] ); 
     75 
     76        Foo c ( * ( v[0] ) ); 
     77        CHECK_EQUAL ( 1, c.get_x() ); 
     78 
     79        const Foo *p = v[1].get(); 
     80        CHECK_EQUAL ( 1, p->get_x() ); 
     81 
     82        CHECK ( v[2].unique() ); 
     83        CHECK_EQUAL ( 2, v[2]->get_x() ); 
     84 
     85        bdm::shared_ptr<Foo> non_const; 
     86        bdm::shared_ptr<const Foo> another ( non_const ); 
     87        CHECK ( !non_const.unique() ); 
     88} 
     89 
    5590TEST ( test_shared_ptr_error ) { 
    5691        bdm::shared_ptr<Foo> empty;