#ifndef INTEGER_SEQUENCE_HPP #define INTEGER_SEQUENCE_HPP #include #include #include #include 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(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(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(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