#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; } friend void swap(IntegerSequence& is1, IntegerSequence& is2) { std::cout << "IntegerSequence: swapping two sequences with " << is1.size << " and " << is2.size << " elements" << std::endl; std::swap(is1.data, is2.data); std::swap(is1.size, is2.size); std::swap(is1.allocated, is2.allocated); } IntegerSequence(IntegerSequence&& other) : IntegerSequence() { swap(*this, other); std::cout << "IntegerSequence: move constructor moving " << size << " elements" << std::endl; } ~IntegerSequence() { std::cout << "IntegerSequence: destructor deleting " << size << " elements" << std::endl; std::free(data); } IntegerSequence& operator=(IntegerSequence other) { std::cout << "IntegerSequence: assignment operator receiving " << other.size << " elements" << std::endl; swap(*this, other); 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