Skip to content
C++ project #24Advanced

Build Your Own std::vector

DynArray<T>: raw storage, placement new, the Rule of Five, geometric growth, move_if_noexcept and the strong exception guarantee — proven by an instrumented test harness.

Estimated time
~8 hours to build
Files
6 files · 577 lines
Technologies
C++17, <new> (placement new), <memory>, <utility>, Header-only template

Introduction

Using std::vector is easy; writing one teaches you how C++ really manages objects. Memory allocation and object lifetime are separate steps, moving is not the same as copying, and a careless line can leak objects or destroy them twice when an exception is thrown. The harness counts every construction, copy, move and destruction to prove the container is correct.

Problem statement

Implement a vector-like class template with push_back/emplace_back, pop_back, erase, clear, reserve, shrink_to_fit, bounds-checked at(), iterators, equality, copy and move construction and assignment. Growth must double the capacity, reallocation must move elements only when their move constructor is noexcept, push_back(a[0]) must be safe during reallocation, and a throwing copy must leave everything unchanged and leak nothing. Write a scenario-based test harness that verifies all of this.

Objectives

  • Separate allocation (operator new) from construction (placement new)
  • Implement the Rule of Five and copy-and-swap
  • Provide the strong exception guarantee
  • Understand std::move_if_noexcept and why vector uses it

Features

  • Geometric (doubling) growth
  • Iterators that work with std::sort, std::find and std::accumulate
  • Exception-safe copy and reallocation
  • Self-referencing push_back is safe
  • 8 test scenarios with pass/fail checks and object counters

Concepts demonstrated

  • Rule of Five
  • Placement new
  • Exception safety guarantees
  • Move semantics
  • Iterators
  • Instrumented testing

System architecture

DynArray<T> holds T* data_, size_ and capacity_. Memory comes from ::operator new (raw bytes) and objects are created with placement new and destroyed with explicit destructor calls, so capacity can exceed size. transfer_to builds elements in a new buffer with std::move_if_noexcept; if any construction throws it destroys what it built and frees the buffer, leaving the original untouched. emplace_back constructs the new element in the new buffer *before* moving the old ones, which makes push_back(a[0]) safe. Assignment takes its argument by value and swaps (copy-and-swap). The harness's Tracked type counts lifecycle events; CopyOnly has a throwing move.

Folder structure

TextProject tree
dynamic-array-container/
├── README.md
├── Makefile
├── src/dyn_array.h
├── src/main.cpp
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

Makefile

20 lines
MakefileMakefile
# Generated for KENHOLT Skills. Usage: make | make test | make clean
CXX = g++
CXXFLAGS = -std=c++17 -Wall -Wextra -O2
SRC := $(wildcard src/*.cpp)
HDR := $(wildcard src/*.h src/*.hpp)
ARGS := $(shell cat tests/args.txt 2>/dev/null)
INPUT := $(wildcard tests/sample-input.txt)
app: $(SRC) $(HDR)
$(CXX) $(CXXFLAGS) -Isrc $(SRC) -o app
test: app
./app $(ARGS) $(if $(INPUT),< $(INPUT),) > actual.txt
diff actual.txt tests/expected-output.txt && echo "Test passed: output matches tests/expected-output.txt"
clean:
rm -f app app.exe actual.txt
.PHONY: test clean

What each file does

src/dyn_array.h
The complete DynArray<T> template: storage management, Rule of Five, growth, modifiers and iterators.
src/main.cpp
Instrumented test types and the eight named scenarios with their checks.
Makefile
Build automation: make builds ./app, make test runs the sample session and compares it with the expected output, make clean removes build files.

How to run it

Build

Terminal
g++ -std=c++17 -Wall -Wextra -Isrc src/*.cpp -o app
# or simply: make

Run

Terminal
./app # Linux / macOS
.\app.exe # Windows

Test against the expected output

Terminal
./app < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt # no output means they match
# Windows PowerShell:
# Get-Content tests\sample-input.txt | .\app.exe > actual.txt
# Compare-Object (Get-Content actual.txt) (Get-Content tests\expected-output.txt)

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
== growth ==
capacities after each push: 1 2 4 4 8 8 8 8 16
squares (size 9, capacity 16): 1 4 9 16 25 36 49 64 81
[pass] capacity doubles: 1 2 4 4 8 8 8 8 16
[pass] shrink_to_fit releases unused capacity
Unknown scenario 'not-a-scenario'. Available: algorithms assignment bounds copy-move exception-safety growth realloc-moves self-reference
== algorithms ==
sorted (size 5, capacity 5): 1 3 5 7 9
[pass] works with std::sort, std::accumulate and std::find
after erase(1) and pop_back (size 3, capacity 5): 1 5 7
[pass] erase shifts elements left
== assignment ==
a after a = b (size 1, capacity 1): 7
a after a = a (size 1, capacity 1): 7
b after move-assign (size 3, capacity 3): 5 6 8
[pass] copy, self and move assignment
[pass] no leaks after assignments
== bounds ==
DynArray::at: index 3 >= size 3
[pass] at() is bounds-checked
DynArray::pop_back on empty array
[pass] pop_back on an empty array throws instead of corrupting memory
== copy-move ==
b (copy) (size 3, capacity 3): 10 20 30
c (moved-to) (size 3, capacity 3): 10 20 30
a (moved-from) (size 0, capacity 0):
[pass] copy is equal, moved-from is empty
[pass] changing the copy doesn't affect the original (deep copy)
constructed 3, copied 3, moved 0
[pass] copy made 3 copies; move constructor made none
[pass] every object was destroyed exactly once
== exception-safety ==
copy threw: copy failed
original after failed copy (size 3, capacity 3): 1 2 3
[pass] the source is untouched
[pass] the partly built copy was cleaned up (no leaks)
== growth ==
capacities after each push: 1 2 4 4 8 8 8 8 16
squares (size 9, capacity 16): 1 4 9 16 25 36 49 64 81
[pass] capacity doubles: 1 2 4 4 8 8 8 8 16
[pass] shrink_to_fit releases unused capacity
== realloc-moves ==
5 emplace_backs: constructed 5, copied 0, moved 7
[pass] reallocation moves (noexcept move): 1 + 2 + 4 = 7 moves, 0 copies
[pass] a type with a throwing move is copied instead (move_if_noexcept)
[pass] no leaks
== self-reference ==
strings (size 5, capacity 8): alpha alpha alpha alpha alpha
[pass] push_back(a[0]) is safe across reallocation
9 scenario(s) run, 0 check(s) failed
Input
# run one scenario by name, or "all"
growth
not-a-scenario
all

Testing

  • Compare ./app < tests/sample-input.txt with tests/expected-output.txt; the run ends with '0 check(s) failed'.
  • growth: capacities go 1 2 4 4 8 8 8 8 16.
  • realloc-moves: five emplace_backs cause exactly 7 moves and 0 copies; a type with a throwing move is copied 7 times instead.
  • exception-safety: when the second copy throws, the source is unchanged and every object is destroyed.

Common errors

Objects destroyed twice / heap corruption

After moving elements to a new buffer you must still destroy the moved-from originals exactly once, then free the old raw memory with operator delete (not delete[]).

Memory leak when a copy constructor throws

A constructor that throws never runs its own destructor; catch, clean up what was built, and rethrow (see copy_from).

Possible improvements

  • Add insert(pos, value) and resize(n)
  • Support custom allocators
  • Add a small-buffer optimisation for short arrays

Additional challenges

  1. 1Make the iterators a class with debug checks for out-of-range access.
  2. 2Add emplace(pos, args...) with the strong guarantee.
  3. 3Benchmark against std::vector with a million push_backs.

Built and tested it yourself? Mark it to update your dashboard.