Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/Patterns/ObservedIterator.hpp

    rf2bb0f r8774c5  
    3636
    3737  ObservedIterator(_Iter iter,Observable *obs) :
    38     iter(iter)
    39   {
    40     // for this we actually get a lock on the heap,
    41     // so we can copy ourselves
    42     protector = new Observable::_Observable_protector(obs);
    43   }
     38    iter(iter),
     39    collection(obs),
     40    protector(0)
     41  {}
    4442
    4543  ObservedIterator(const ObservedIterator &dest) :
    46     iter(dest.iter)
    47   {
    48     protector = new Observable::_Observable_protector(*dest.protector);
    49   }
     44    iter(dest.iter),
     45    collection(dest.collection),
     46    protector(dest.copyLock())
     47  {}
    5048
    5149  ~ObservedIterator(){
     
    5856    if(&dest !=this){
    5957      // get the new lock first, in case the two locks point to the same observable
    60       Observable::_Observable_protector *newLock = new Observable::_Observable_protector(*dest.protector);
    61       delete protector;
     58      Observable::_Observable_protector *newLock = dest.copyLock();
     59      if(protector)
     60        delete protector;
    6261      protector = newLock;
    6362      // After the new lock is aquired we can safely set the iterator
    6463      iter = dest.iter;
     64      // we need to know the collection, in case we still have to set the lock
     65      collection = dest.collection;
    6566    }
    6667    return *this;
     
    8384  {
    8485    --iter;
     86    return *this;
    8587  }
    8688
     
    101103
    102104  value_type operator*(){
     105    // access is requested... time to get the lock
     106    acquireLock();
    103107    return (*iter);
     108  }
     109
     110  value_type *operator->(){
     111    acquireLock();
     112    return &(*iter);
    104113  }
    105114
     
    111120
    112121private:
     122
     123  /**
     124   * gets the lock for the collection when needed
     125   *
     126   * The lock is only acquired when the first change is done, so we can be free to do
     127   * anything with the iterator before that. I.e. step forward, turn into a const_iterator
     128   * etc.
     129   */
     130  void acquireLock(){
     131    if(!protector)
     132      protector = new Observable::_Observable_protector(collection);
     133  }
     134
     135  Observable::_Observable_protector *copyLock() const{
     136    // we only copy if we actually carry a lock
     137    if(protector){
     138      return new Observable::_Observable_protector(*protector);
     139    }
     140    else{
     141      return 0;
     142    }
     143  }
     144
    113145  _Iter iter;
     146  Observable *collection;
    114147  Observable::_Observable_protector *protector;
    115148};
Note: See TracChangeset for help on using the changeset viewer.