teaching machines

CS 330 Lecture 25 – A Compiler That’s For You

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

Agenda

What’s Wrong With This?

What things are wrong with this code?

class SVector {
public:
  SVector(int n) :
    n(n),
    coords(new int[n]) {
    for (int i = 0; i < n; ++i) {
      coords[i] = rand();
    }
  }

  int& operator[](int i) const {
    assert(i >= 0 && i < n);
    return coords[i];
  }

private:
  int coords;
};

int main() {
  while (listen_for_client()) {
    SVector v(10);
    spawn_client_thread(v);
  }
}[/precode]

What Does This Do?

#include <iostream>

class A {
  private:
    int i;

  public:
    A(int i) :
      i(i) {
      std::cout << "in int ctor" << std::endl;
    }

    A(const A& other) :
      i(other.i) {
      std::cout << "in copy ctor" << std::endl;
    }

    A& operator=(const A& a) {
      i = a.i;
      std::cout << "in equals" << std::endl;
    }
};

A give() { return A(7); }
void take(A param) {}

int main(int argc, char **argv) {
  /* A bunch_of_as[3]; */
  /* A a(6); */
  /* A b = a;  */
  /* A c = give(); */
  /* b = c; */
  /* A d = 7; */
  /* take(3); */
  return 0;
}

Think About This

You have a 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 2.
  2. In what situations does the number of references decrease? I can think of 2.

Code

SVector.cpp

#include <iostream>
#include <cstdlib>

using std::cout;

class SVector {
public:
  SVector(int n) :
    n(n),
    coords(new int[n]) {
    for (int i = 0; i < n; ++i) {
      coords[i] = rand();
    }
  }

  ~SVector() {
    /* delete[] coords; */
  }

  int operator[](int i) const {
    return coords[i];
  }

private:
  int *coords;
  int n;
};

int main() {
  for (int i = 0; i < 10; ++i) {
    SVector v(100);
    cout << v[0] << std::endl;
  }
}

foo.cpp

#include <iostream>

class A {
  private:
    int i;

  public:
    /*explicit*/ A(int i) :
      i(i) {
      std::cout << "in int ctor" << std::endl;
    }

    A(const A& other) :
      i(other.i) {
      std::cout << "in copy ctor" << std::endl;
    }

    A& operator=(const A& a) {
      i = a.i;
      std::cout << "in equals" << std::endl;
      return *this;
    }
};

class B {
  public:
    B(int i) {}
};

A give() { A a = A(7); return a; }
void take(A param) {}
void take(B param) {}

int main(int argc, char **argv) {
  /* A bunch_of_as[3]; */
  /* A a(6); */
  /* A b = a;  */
  /* A b(a);  */
  /* A c = give(); */
  /* A c(9); */
  /* b = c; */
  /* A d = 7; */
  /* std::string s = "foo"; */
  take(3);
  return 0;
}

Haiku

You can kill them off
Or let them live, forgotten
Or there's seppuku