C++ · Module 19 · Lesson 61 min read

Project: Build Your Own Generic Container

Goal

Implement DynamicArray<T> that behaves like a simplified std::vector<T>.

Features checklist

  1. push_back (copy and move), emplace_back, pop_back
  2. operator[] (unchecked) and at() (throws std::out_of_range)
  3. size(), capacity(), empty(), reserve(), clear()
  4. Growth: double the capacity when full (amortized O(1) push)
  5. Rule of Five: destructor, copy constructor, copy assignment, move constructor, move assignment
  6. Iterators: begin()/end() returning T* (pointers are random-access iterators!) → works with std::sort, std::find, range-for
  7. operator==, initializer-list constructor

Memory strategy

Allocate raw memory with std::allocator<T> (or ::operator new) and construct elements only when added, using std::construct_at / placement new, and destroy them with std::destroy_at. This way capacity slots don't need a default-constructible T.

Simpler version for learning: std::unique_ptr<T[]> with new T[cap] — requires default-constructible T.

Growth step

  1. Allocate a bigger block
  2. Move existing elements over (std::move_if_noexcept for the strong guarantee)
  3. Destroy the old elements and free the old block

Testing checklist ✅

  • Works with int, std::string, and a type that counts copies/moves
  • Self-assignment, copying an empty array, moving leaves the source empty
  • Runs clean under AddressSanitizer (no leaks, no double frees)

Extensions

insert/erase at a position, resize, a proper iterator class with debug checks, shrink_to_fit, comparison with <=>, a custom allocator parameter.

Example

C++
#include <algorithm>
#include <initializer_list>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>

template <typename T>
class DynamicArray {
public:
    DynamicArray() = default;
    DynamicArray(std::initializer_list<T> init) { reserve(init.size()); for (const T& x : init) push_back(x); }
    ~DynamicArray() { clear(); alloc_.deallocate(data_, cap_); }

    DynamicArray(const DynamicArray& o) { reserve(o.size_); for (const T& x : o) push_back(x); }
    DynamicArray(DynamicArray&& o) noexcept
        : data_(std::exchange(o.data_, nullptr)), size_(std::exchange(o.size_, 0)), cap_(std::exchange(o.cap_, 0)) {}
    DynamicArray& operator=(DynamicArray o) noexcept {          // copy-and-swap covers copy and move assignment
        std::swap(data_, o.data_); std::swap(size_, o.size_); std::swap(cap_, o.cap_);
        return *this;
    }

    void push_back(const T& x) { emplace_back(x); }
    void push_back(T&& x) { emplace_back(std::move(x)); }
    template <typename... Args>
    T& emplace_back(Args&&... args) {
        if (size_ == cap_) reserve(cap_ == 0 ? 1 : cap_ * 2);   // geometric growth
        T* slot = std::construct_at(data_ + size_, std::forward<Args>(args)...);
        ++size_;
        return *slot;
    }
    void pop_back() { if (size_ == 0) throw std::out_of_range("pop_back on empty"); std::destroy_at(data_ + --size_); }

    void reserve(std::size_t new_cap) {
        if (new_cap <= cap_) return;
        T* fresh = alloc_.allocate(new_cap);
        for (std::size_t i = 0; i < size_; ++i) {
            std::construct_at(fresh + i, std::move_if_noexcept(data_[i]));
            std::destroy_at(data_ + i);
        }
        alloc_.deallocate(data_, cap_);
        data_ = fresh;
        cap_ = new_cap;
        ++reallocations;
    }
    void clear() { std::destroy(data_, data_ + size_); size_ = 0; }

    T& operator[](std::size_t i) { return data_[i]; }
    const T& operator[](std::size_t i) const { return data_[i]; }
    T& at(std::size_t i) { if (i >= size_) throw std::out_of_range("index " + std::to_string(i)); return data_[i]; }
    std::size_t size() const { return size_; }
    std::size_t capacity() const { return cap_; }
    bool empty() const { return size_ == 0; }

    T* begin() { return data_; }                  // raw pointers are random-access iterators
    T* end() { return data_ + size_; }
    const T* begin() const { return data_; }
    const T* end() const { return data_ + size_; }

    friend bool operator==(const DynamicArray& a, const DynamicArray& b) {
        return std::equal(a.begin(), a.end(), b.begin(), b.end());
    }
    int reallocations = 0;

private:
    std::allocator<T> alloc_;
    T* data_ = nullptr;
    std::size_t size_ = 0, cap_ = 0;
};

struct Tracked {                                  // counts copies vs moves
    std::string name;
    explicit Tracked(std::string n) : name(std::move(n)) {}
    Tracked(const Tracked& o) : name(o.name) { ++copies; }
    Tracked(Tracked&& o) noexcept : name(std::move(o.name)) { ++moves; }
    Tracked& operator=(const Tracked&) = default;
    static inline int copies = 0, moves = 0;
};

int main() {
    DynamicArray<int> nums = { 42, 7, 93, 15 };
    for (int i = 0; i < 6; ++i) nums.push_back(i * 10);
    std::cout << "size " << nums.size() << ", capacity " << nums.capacity() << '\n';
    std::sort(nums.begin(), nums.end());                         // STL algorithm on our container
    std::cout << "sorted:";
    for (int x : nums) std::cout << ' ' << x;                    // range-for works
    std::cout << "\nfind 93 at index " << std::find(nums.begin(), nums.end(), 93) - nums.begin() << '\n';

    try { nums.at(50); } catch (const std::out_of_range& e) { std::cout << "at() threw: " << e.what() << '\n'; }

    DynamicArray<int> copy = nums;
    copy[0] = -1;
    std::cout << "copy is independent? " << std::boolalpha << !(copy == nums) << '\n';
    DynamicArray<int> moved = std::move(copy);
    std::cout << "after move: moved.size() " << moved.size() << ", copy.size() " << copy.size() << '\n';
    nums = nums;                                                 // self-assignment is safe
    std::cout << "after self-assignment size " << nums.size() << '\n';

    DynamicArray<Tracked> items;
    for (int i = 0; i < 100; ++i) items.emplace_back("item" + std::to_string(i));
    std::cout << "100 emplace_backs: " << items.reallocations << " reallocations, copies "
              << Tracked::copies << ", moves " << Tracked::moves << " (noexcept move used)\n";

    DynamicArray<std::string> words = { "save", "spend", "track" };
    words.pop_back();
    std::cout << "words:";
    for (const auto& w : words) std::cout << ' ' << w;
    std::cout << '\n';
    return 0;
}

/* Output:
size 10, capacity 16
sorted: 0 7 10 15 20 30 40 42 50 93
find 93 at index 9
at() threw: index 50
copy is independent? true
after move: moved.size() 10, copy.size() 0
after self-assignment size 10
100 emplace_backs: 8 reallocations, copies 0, moves 127 (noexcept move used)
words: save spend
*/