1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
#ifndef INTEGER_SEQUENCE_HPP
#define INTEGER_SEQUENCE_HPP

#include <cassert>
#include <cstdlib>
#include <new>
#include <iostream>

class IntegerSequence {
   public:
      IntegerSequence() : data{nullptr}, size{0}, allocated{0} {
	 std::cout << "IntegerSequence: default constructor" << std::endl;
      }
      IntegerSequence(const IntegerSequence& other) :
	    data{
	       other.data?
		  static_cast<int*>(std::malloc(other.allocated * sizeof(int)))
	       :
		  nullptr
	    }, size{other.size}, allocated{other.allocated} {
	 if (size > 0 && !data) {
	    throw std::bad_alloc();
	 }
	 for (std::size_t i = 0; i < size; ++i) {
	    data[i] = other.data[i];
	 }
	 std::cout << "IntegerSequence: copy constructor copying "
	    << size << " elements" << std::endl;
      }
      ~IntegerSequence() {
	 std::cout << "IntegerSequence: destructor" << std::endl;
	 std::free(data);
      }
      IntegerSequence& operator=(const IntegerSequence& other) {
	 if (other.size > allocated) {
	    int* newdata = static_cast<int*>(std::realloc(data,
	       other.allocated * sizeof(int)));
	    if (!newdata) {
	       throw std::bad_alloc();
	    }
	    data = newdata; allocated = other.allocated;
	 }
	 size = other.size;
	 for (std::size_t i = 0; i < size; ++i) {
	    data[i] = other.data[i];
	 }
	 std::cout << "IntegerSequence: assignment operator copying "
	    << size << " elements" << std::endl;
	 return *this;
      }

      void add(int value) {
	 if (size == allocated) {
	    std::size_t newsize = allocated * 2 + 8;
	    int* newdata = static_cast<int*>(std::realloc(data,
	       newsize * sizeof(int)));
	    if (!newdata) {
	       throw std::bad_alloc();
	    }
	    data = newdata;
	    allocated = newsize;
	 }
	 data[size++] = value;
      }
      std::size_t length() const {
	 return size;
      }
      int& operator()(std::size_t index) {
	 assert(index < size);
	 return data[index];
      }
      const int& operator()(std::size_t index) const {
	 assert(index < size);
	 return data[index];
      }
   private:
      int* data;
      std::size_t size;
      std::size_t allocated;
};

#endif