Facebook Pixel

You are on level: Student

0%
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section

Vector Growth Tracker

Prerequisites: vector Size, Capacity, Growth, and reserve, Copies, Moves, and Object Layout, Move Semantics Without Magic

A strategy appends every AAPL MarketUpdate it receives to a std::vector. Most of those push_back calls write into spare capacity. A few allocate a larger buffer and relocate every element already stored.

Whether relocation moves or copies depends on one keyword on the element type's move constructor. Build a smaller std::vector that makes each of those steps visible.

What to implement

  • Write the class template Vector<T> at global scope. You write only the class, and the editor already declares every member the driver calls.
  • A hidden driver instantiates it with two element types and runs it through a list of commands. It prints every allocation and every element construction, copy, move, and destruction that happens inside a Vector member.
  • <new>, <utility>, <memory>, and <type_traits> are already included. #include any other header you need at the top of your code.
  • On stdin, the first line is the number of commands, and each remaining line is one command.
  • There are three parts. One solution must pass all ten tests.
MemberContractCalled by
Vector()Empty: size 0, capacity 0, no buffer. Allocates nothing.make
~Vector()Destroys the elements from index 0 upward, then frees the buffer if there is one.drop, end of input
void push_back(const T& value)Appends a copy of value.push, dup
void push_back(T&& value)Appends an element move-constructed from value.pushmove
template <class... Args> T& emplace_back(Args&&... args)Appends T(std::forward<Args>(args)...) and returns a reference to the new element.emplace, emplacemove
void pop_back()Destroys the last element. The capacity is unchanged.pop
void clear()Destroys every element from index 0 upward. The size becomes 0; the buffer and the capacity are kept.clear
std::size_t size() const and std::size_t capacity() constThe number of elements stored, and the number of slots in the buffer.size
T& operator[](std::size_t i) and const T& operator[](std::size_t i) constElement i.dup, get
  • The starter deletes the copy constructor and copy assignment. The driver never copies or moves a Vector.
  • The driver checks at compile time that emplace_back returns T&, that the const operator[] returns const T&, and that size() and capacity() are const members returning std::size_t.
  • A failed check is a compile error in driver.cpp (the hidden driver) whose message names the rule.

Commands

  • Each command is one line. Slots are named by one lowercase letter.
  • A slot is either absent or holds one Vector of one element type, written T below. Ids are positive integers.
  • Every command is valid for the slot it names: the slot exists, every index is less than size(), and pop never runs on an empty vector.
CommandWhat the driver runsPrints
make s nothrow or make s throwingVector<Nothrow> s; or Vector<Throwing> s;events
push s idT t(id); s.push_back(t);events
pushmove s idT t(id); s.push_back(std::move(t));events
emplace s ids.emplace_back(id);events
emplacemove s idT t(id); s.emplace_back(std::move(t));events
dup s is.push_back(s[i]);events
pop ss.pop_back();events
clear ss.clear();events
get s is[i], through a const references[i] = id
size ss.size() and s.capacity()s size n cap c
drop ss goes out of scope: its destructor runs and the slot becomes absent.events

Events

The events are these lines, printed in the order they happen:

LinePrinted when
alloc k::operator new allocates room for k elements, that is k * sizeof(T) bytes.
free k::operator delete frees a buffer of k elements.
ctor idA T is constructed from an int.
copy idA T is copy-constructed.
move idA T is move-constructed. The source's id becomes 0.
dtor idA T is destroyed.

A correct class prints nothing else. The driver also reports mistakes it can detect:

  • assign id when an element is assigned to instead of constructed;
  • double free k when a buffer is freed twice, and free ? when the class frees memory it did not allocate;
  • a line saying so when emplace_back returns a reference to anything other than the new last element.

The driver never returns memory to the system, so a double free does not crash the run.

After the last command:

  1. The driver prints end.
  2. The remaining vectors go out of scope in reverse order of creation, the way local variables die at a closing brace.
  3. The driver prints allocs A frees F: the number of alloc and free lines in the whole test. A class that frees everything it allocates prints two equal numbers.

The element types

The driver defines Tracked<bool NoexceptMove>, a struct with one field, int id, and two aliases for it.

  • Nothrow is Tracked<true>, whose move constructor is noexcept.
  • Throwing is Tracked<false>, whose move constructor runs the same code without noexcept, so std::is_nothrow_move_constructible_v<Throwing> is false.
  • Neither type has a default constructor.
  • Both print a line when an object is constructed, copied, moved, or destroyed, but only while a Vector member is running. The driver's own objects, such as the argument it passes to push_back, are made and destroyed silently.
  • A move leaves the source's id at 0, so destroying a moved-from object prints dtor 0.

Raw storage

A vector's buffer has room for capacity() elements but holds live objects only in its first size() slots. Allocating memory and constructing objects are therefore separate steps, and each of these expressions does one step:

ExpressionWhat it does
static_cast<T*>(::operator new(n * sizeof(T)))Allocates raw memory for n elements and constructs nothing. std::allocator<T>().allocate(n) does the same through the default allocator.
::new (static_cast<void*>(p)) T(args)Placement new: constructs a T in the already allocated memory at p. It allocates nothing.
p->~T()Runs the destructor of the object at p and frees nothing.
::operator delete(p)Frees raw memory and destroys nothing.
  • new T[n] cannot replace the first expression. It constructs n elements at once, and neither element type has a default constructor, so it does not compile.
  • emplace_back is a function template whose parameter Args&&... args is a parameter pack: it accepts any number of arguments of any types.
  • std::forward<Args>(args)... passes each argument on with the value category it arrived with. So T(std::forward<Args>(args)...) copies from an lvalue argument and moves from an rvalue one. This is called perfect forwarding.
  • Writing T(args...) instead copies from rvalues too, because a named parameter is an lvalue.

Part 1: Growth and relocation

Implement the members in the class table, following these rules.

  1. Every append (push_back or emplace_back) checks for room first.
  2. When size() < capacity(), it constructs the new element in the slot at index size() and allocates nothing.
  3. When size() == capacity(), the vector is full and grows. The new capacity is 1 if the capacity is 0 and twice the capacity otherwise, so a vector filled one element at a time has capacity 1, 2, 4, 8, and so on.

Growing performs these steps in this order:

  1. Allocate one raw buffer for the new capacity.
  2. Construct the new element at index size() of the new buffer.
  3. Relocate the old elements into the same indices of the new buffer, from index 0 upward.
  4. Destroy the old elements, from index 0 upward.
  5. Free the old buffer. A vector whose capacity was 0 has no buffer to free.

Step 2 comes before step 3 because the argument may be an element of the same vector, as in v.push_back(v[0]), the call dup runs.

Until step 4 every old element is still alive, so the new element is built from a valid source. Relocating first would read v[0] after it had been moved from or destroyed.

Relocation. Relocating element i means ::new (static_cast<void*>(fresh + i)) T(std::move_if_noexcept(old[i])). As Move Semantics Without Magic explains, std::move_if_noexcept yields:

  • an rvalue, so the move constructor runs, when T's move constructor is noexcept;
  • a const lvalue, so the copy constructor runs, otherwise.

For Nothrow, step 3 prints move lines and step 4 prints dtor 0 for each moved-from original. For Throwing, step 3 prints copy lines and step 4 destroys originals that are still intact.

The rule covers relocation only. push_back(T&&) moves its argument even for Throwing, because the old elements are untouched while the new element is built.

Tests 1–5 cover this part.

Part 2: reserve

reserve allocates the buffer up front so that later appends do not grow.

MemberContractCalled by
void reserve(std::size_t n)If n <= capacity(), does nothing. Otherwise sets the capacity to exactly n with steps 1, 3, 4, and 5 of growth: allocate, relocate, destroy the old elements, and free the old buffer. The size is unchanged.reserve s n
  • The new command is reserve s n, which runs s.reserve(n); and prints events.
  • After reserve(n), the next n - size() appends allocate nothing.
  • Growth then doubles from the reserved capacity, so a vector reserved to 3 grows to 6.

Tests 6–7 and 10 cover this part.

Part 3: shrink_to_fit

shrink_to_fit gives spare capacity back.

MemberContractCalled by
void shrink_to_fit()If capacity() == size(), does nothing. If the vector is empty, frees the buffer and sets the capacity to 0 without allocating. Otherwise sets the capacity to exactly size() with steps 1, 3, 4, and 5 of growth.shrink s
  • The new command is shrink s, which runs s.shrink_to_fit(); and prints events.
  • std::vector::shrink_to_fit is a non-binding request that a library may ignore. This one always gives the spare capacity back.

Tests 8–9 cover this part.

Example
Input
7
make a nothrow
emplace a 1
pushmove a 2
make b throwing
emplace b 1
pushmove b 2
size b
Output
alloc 1
ctor 1
alloc 2
move 2
move 1
dtor 0
free 1
alloc 1
ctor 1
alloc 2
move 2
copy 1
dtor 1
free 1
b size 2 cap 2
end
dtor 1
dtor 2
free 2
dtor 1
dtor 2
free 2
allocs 4 frees 4
Explanation

The first append to each empty vector allocates one slot and constructs element 1 there.

The second append finds the vector full and grows it to 2. It allocates the new buffer, builds element 2 in slot 1 with move 2, relocates element 1, destroys the original, and frees the old one-slot buffer.

The two vectors differ only in step 3. Nothrow relocates element 1 with move 1, so the original it destroys is a moved-from object (dtor 0). Throwing relocates it with copy 1, so the original is still intact when destroyed (dtor 1).

Element 2 is moved in both vectors, because pushmove builds the new element from an rvalue and no old element is at risk. At the end, b goes out of scope before a because it was created later.