diff --git a/Vector.h b/Vector.h index 1ea8a38..3de0eab 100644 --- a/Vector.h +++ b/Vector.h @@ -10,13 +10,14 @@ class Vector { // If the needed capacity is known, it can be passed; other wise, a default // capacity is reserved. Vector(unsigned int capacity = 10) - : capacity(capacity), element_count(0), data(new T[capacity]) { + : capacity(capacity), element_count(0), + data((T *)::operator new(capacity * sizeof(T))) { } // Copy Constructor Vector(const Vector &other) : capacity(other.capacity), element_count(other.element_count), - data(new T[capacity]) { + data((T *)::operator new(capacity * sizeof(T))) { // `std::copy` is used because it is more flexible than `std::memcpy`, // and the compiler will replace it with `memcpy` anyway if appropriate, // so there is no performance loss. @@ -24,7 +25,7 @@ class Vector { } // Move Constructor using the copy-and-swap-idiom - Vector(Vector &&other) : data(new T[capacity]) { + Vector(Vector &&other) : data((T *)::operator new(capacity * sizeof(T))) { swap(*this, other); } @@ -175,7 +176,7 @@ class Vector { // Note that this function doesn't validate its input for optimization // reasons! void reallocate(unsigned int new_size) { - T *new_data = new T[new_size]; + T *new_data = (T *)::operator new(new_size * sizeof(T)); std::copy(data, data + element_count, new_data); delete[] data; diff --git a/test.cpp b/test.cpp index 87e69e4..1947a22 100644 --- a/test.cpp +++ b/test.cpp @@ -236,3 +236,25 @@ SCENARIO("Resizing a vector", "[vector]") { } } } + +SCENARIO("Non-default constructor", "[vector]") { + GIVEN("A class object with a non-default constructor") { + class NonDefault { + public: + NonDefault(int a) : a(a) { + } + + int a; + }; + + WHEN("Creating a vector and adding an element") { + Vector non_default_vector; + + non_default_vector.push_back(NonDefault(1)); + + THEN("The element should be accessible as usual") { + REQUIRE(non_default_vector[0].a == 1); + } + } + } +} \ No newline at end of file