All pastes #909816 Raw Edit

Anonymous

public text v1 · immutable
·published 2008-02-19 15:08 UTC
rendered paste body
template <typename T>
class shared_ptr {
  T* p_;
  mutable const shared_ptr<T>* next_;
  mutable const shared_ptr<T>* prev_;
  
public:
  shared_ptr() : p_(0), next_(0), prev_(0) { }
  explicit shared_ptr(T* p) : p_(p), next_(0), prev_(0) { }
  shared_ptr(const shared_ptr<T>& p) : p_(p.p_), next_(p.next_), prev_(&p) {
    if (p.next_) {
      p.next_->prev_ = this;
    }
    p.next_ = this;
  }

  ~shared_ptr() {
    if (p_) {
      if (prev_) { prev_->next_ = next_; }
      if (next_) { next_->prev_ = prev_; }
      if (!next_ && !prev_) {
        delete p_;
      }
    }
  }

  void swap(shared_ptr<T>& other) {
    std::swap(p_, other.p_);
    std::swap(next_, other.next_);
    if (next_) { next_->prev_ = this; }
    if (other.next_) { other.next_->prev_ = &other; }
    std::swap(prev_, other.prev_);
    if (prev_) { prev_->next_ = this; }
    if (other.prev_) { other.prev_->next_ = &other; }
  }

  shared_ptr<T>& operator=(const shared_ptr<T>& other) {
    if (p_ == other.p_) {
      return *this;
    } else {
      shared_ptr<T> temp(other);
      temp.swap(*this);
      return *this;
    }
  }

  T* operator->() const { return p_; }
  T& operator*() const { return *p_; }
};