All pastes #944497 Raw Edit

Someone

public text v1 · immutable
·published 2008-03-16 03:47 UTC
rendered paste body
// Question 1. How many StringReference OBJECTS are created by the execution of this program? _____
// Question 2. What does the program print? Draw a box around your answer.
#import <iostream>
using namespace std;

class String { 
private:
  class StringReference;
  void  reassign (StringReference *);
  class StringReference {
  public:
    int count;
    char *buffer;
    StringReference(const char *right);
    ~StringReference() { delete [] buffer; }
  };
public:
  int getCount() { if(p) return p->count; else return 0; }
  String () : p(0) { } 
  String (const char * right) : p(0){
    reassign(new StringReference(right)); 
  }
  String (const String & right) : p(0){
    reassign(right.p); 
  }
  ~String () { reassign(0); } 
  void operator = (const String & right) {
    reassign(right.p); 
  }
  StringReference *p;
};



String::StringReference::StringReference(const char *right) {
  count = 0;
  buffer = new char[1 + strlen(right)];
  strcpy(buffer, right);
}

void String::reassign(String::StringReference *np) {
  if (np)
    np->count += 1;
  if (p) {
    p->count -= 1;
    if (p->count == 0)
      delete p;
  }
  p = np;
}
  
String g;

int main() {
  String a = "abc";
  String b = "xyz";
  String c;
  c = a;
  a = b;
  g = c;

  cout << a.getCount() << " " << b.getCount() << " ";
  cout << c.getCount() << " " << g.getCount() << " " << endl;
  return 0;
}