From 1a0b3697f20dc11e7031bf28dd3435e4de7f5952 Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Sat, 11 Jan 2025 17:13:50 +0100 Subject: [PATCH] Constuctor chaining, better/more efficient moving --- vector/vec.cc | 29 +++++++++++++++++++---------- vector/vec.h | 4 +++- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/vector/vec.cc b/vector/vec.cc index 2df75a8..5cbddb4 100644 --- a/vector/vec.cc +++ b/vector/vec.cc @@ -2,14 +2,16 @@ #include #include #include +#include -Vec::Vec() : cap(INITIAL_LEN), w_idx(0), arr(nullptr) { - std::cout << "Allocating vector" << std::endl; - arr = new T[INITIAL_LEN]; +Vec::Vec() : Vec(INITIAL_LEN) {} + +Vec::Vec(std::size_t size) : cap(size), w_idx(0), arr(new T[size]) { + std::cout << "Allocating vector of size " << size << std::endl; } -Vec::Vec(std::initializer_list il) : Vec() { - for (auto &a : il) push_back(a); +Vec::Vec(std::initializer_list il) : Vec(il.size()) { + for (auto &elem : il) push_back(std::move(elem)); } Vec::~Vec() { @@ -26,12 +28,18 @@ T &Vec::operator[](std::size_t idx) const noexcept { exit(1); } -void Vec::push_back(const T &value) noexcept { +void Vec::push_back(const T &value) { arr[w_idx++] = value; - if (w_idx == cap) { + if (w_idx == cap) + resize(cap * 2); +} + +void Vec::push_back(T &&value) { + arr[w_idx++] = std::move(value); + + if (w_idx == cap) resize(cap * 2); - } } std::size_t Vec::size() const { return w_idx; } @@ -39,9 +47,10 @@ std::size_t Vec::size() const { return w_idx; } std::size_t Vec::capacity() const noexcept { return cap; } void Vec::resize(std::size_t newsize) { - std::cout << "Reallocating" << std::endl; + std::cout << "Reallocating: " << cap << " to " << newsize << std::endl; + T *newarr = new T[newsize]; - std::memcpy(newarr, arr, w_idx); + std::move(arr, arr + w_idx, newarr); delete[] arr; arr = newarr; cap = newsize; diff --git a/vector/vec.h b/vector/vec.h index 5154bc7..fd5b060 100644 --- a/vector/vec.h +++ b/vector/vec.h @@ -13,6 +13,7 @@ class Vec { public: Vec(); + explicit Vec(std::size_t); Vec(std::initializer_list); Vec(const Vec &other); // Copy Vec(Vec &&other) noexcept; // Move @@ -25,7 +26,8 @@ class Vec { std::size_t size() const; std::size_t capacity() const noexcept; - void push_back(const T &value) noexcept; + void push_back(const T &value); // May except + void push_back(T &&value); void pop_back() noexcept; void clear() noexcept;