teaching machines

CS 330 Lecture 26 – Reference Counting and Templates

April 4, 2014 by . Filed under cs330, lectures, spring 2014.

Agenda

Think About This

You have a dynamically-allocated, shared resource, accessible through a variable. You’d like this resource to automatically release itself when it is no longer referred to by any external entity. Answer the following questions, thinking about the lifecycle of a variable:

  1. In what situations does the number of references increase? I can think of 3.
  2. In what situations does the number of references decrease? I can think of 2 || 3.

Code

SharedPointer.h

#ifndef SHAREDPOINTER_H
#define SHAREDPOINTER_H

#include <cstdlib>

template<typename T>
class SharedPointer {
  public:
    SharedPointer(T *p) :
      p(p),
      nPatrons(new int(1)) {
    }

    SharedPointer(const SharedPointer<T>& other) :
      p(other.p),
      nPatrons(other.nPatrons) {
      ++*nPatrons;
    }

    ~SharedPointer() {
      Depatron();
    }

    SharedPointer<T>& operator=(const SharedPointer<T>& other) {
      /* ++*(other.nPatrons); */

      // if we're not doing self-assignment, overwrite lhs with rhs
      if (this != &other) {
        Depatron();
        p = other.p;
        nPatrons = other.nPatrons;
        ++*nPatrons;
      }

      return *this;
    }

    T *operator->() {
      return p;
    }

    T& operator*() {
      return *p;
    }

  private:
    void Depatron() {
      --*nPatrons;
      if (*nPatrons == 0) {
        delete p;
        delete nPatrons;
        p = nPatrons = NULL;
      }
    }

    T *p;
    int *nPatrons;
};

#endif

test_shared.cpp

#include <iostream>

#include "SharedPointer.h"

int main(int argc, char **argv) {
  SharedPointer<int> i(new int);
  *i = 7;
  return 0;
}

Haiku

We can kill them off
Or let them live, forgotten
Or there’s seppuku
She wore the red A
So did he, so did their grave
The memory leaked