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

Rule-of-Five Buffer

Prerequisites: Move Semantics Without Magic, RAII: Cleanup That Happens Automatically, Raw Pointers, unique_ptr, shared_ptr, and weak_ptr

A strategy keeps the last few AAPL trade prices in a small buffer, each price an integer number of cents (18950 is $189.50). Build the buffer class with all five special members written by hand.

The buffer owns a heap array, so it needs a destructor that frees the array. Once it has that destructor, the compiler-generated copy constructor and copy assignment are wrong: they copy the pointer, two buffers end up owning one array, and both free it.

  • Rule of five: a class that needs a hand-written destructor almost always needs a hand-written copy constructor, copy assignment, move constructor, and move assignment as well. The first three on their own are called the rule of three.

What to implement

  • Write the class PriceBuffer at global scope. You write only the class.
  • A hidden driver runs it through a list of commands and prints every array it allocates and frees.
  • The editor already declares every member the driver calls, and four small accessors are already written.
  • <algorithm>, <cstddef>, and <utility> are included, so std::copy, std::size_t, std::swap, std::exchange, and std::move are available. #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 two parts. One solution must pass all nine tests.

The class

  • A PriceBuffer holds a pointer data_ and a length size_.
  • A buffer of size 0 is empty: its pointer is nullptr and it owns no array.
  • Every other buffer owns exactly one array of size_ ints, allocated with new int[n] and freed with delete[]. An array from new[] must be freed with delete[], never plain delete.
  • No member allocates an array of length 0, and no member uses the heap in any other way.
MemberContractCalled by
explicit PriceBuffer(std::size_t n)n prices, all 0. For n == 0 the buffer is empty; otherwise it allocates one array with new int[n](), where the trailing () sets every element to 0.make s n
~PriceBuffer()Frees the array, if there is one.drop s, end of input
PriceBuffer(const PriceBuffer& other)A deep copy: a new array with other's length and values. Copying an empty buffer allocates nothing.copy d s
PriceBuffer& operator=(const PriceBuffer& other)Makes *this an independent copy of other, with the strong exception guarantee (below). Assigning a buffer to itself changes nothing and allocates nothing.assign d s, selfassign s
void swap(PriceBuffer& other) noexceptExchanges the contents of the two buffers. Allocates and frees nothing.swap a b
int& operator[](std::size_t i) and const int& operator[](std::size_t i) constElement i. Already written.set, print
std::size_t size() const noexceptThe number of elements. Already written.set, print
const int* data() const noexceptThe array, or nullptr when empty. Already written.print

The driver checks at compile time that:

  • PriceBuffer can be copy constructed and copy assigned;
  • both move operations and swap are noexcept;
  • the std::size_t constructor is explicit, and the two operator[] overloads return int& and const int&.

A failed check is a compile error in driver.cpp (the hidden driver) whose message names the rule.

Copy assignment and exceptions

When new cannot allocate, it throws std::bad_alloc. Copy assignment must give the strong exception guarantee: if it throws, *this is left exactly as it was before the call. So, unless other is *this:

  1. It allocates the new array and copies other's values into it before it changes *this or frees anything.
  2. Only then does *this take the new array.
  3. The old array, if any, is freed.
  • A copy assignment from a non-empty buffer always allocates a new array, even when both buffers have the same length. It prints new[] first and then delete[] (the second only if *this held an array).
  • A copy assignment from an empty buffer allocates nothing, frees the old array, and leaves *this empty.

Commands

  • Each command is one line. Slots are named by one lowercase letter.
  • A slot is either absent or holds one PriceBuffer, which may be empty.
  • make, copy, and move name an absent target slot; every other slot a command names is present. assign, moveassign, and swap name two different slots.
  • set uses an index below the buffer's size, and every value fits in an int.
CommandWhat the driver runsPrints
make s nPriceBuffer s(n);events
set s i vs[i] = v;nothing
print sReads s.size(), s.data(), and every s[i] through a const reference.print s #k [v0 v1 ...], or print s null [] when empty
copy d sPriceBuffer d(s);events
assign d sd = s;events
selfassign ss = s;events
swap a ba.swap(b);events
drop ss goes out of scope: its destructor runs and the slot becomes absent.events
failThe next array allocation made inside a PriceBuffer member throws std::bad_alloc.nothing

Events

The driver replaces the global operator new and operator delete and prints these events:

What happensPrinted line
a PriceBuffer member allocates an array of n intsnew[] #k size n, where #k is the next number: #1, #2, and so on
array #k is freed with delete[]delete[] #k
the next array allocation after failnew[] size n fails, with no number, then std::bad_alloc is thrown
  • In a print line, #k names the array that data() returns. A copy shows a different number from its source, and two buffers never show the same number.
  • Commands that allocate nothing leave a pending fail waiting for the next allocation: selfassign, swap, set, print, drop, a make of size 0, a copy or assign from an empty buffer, and in Part 2 move and moveassign.
  • When the exception reaches the driver, it prints caught bad_alloc and moves on to the next command. A make or copy that throws leaves its target slot absent; an assign that throws leaves both buffers as they were.

End of input

  1. The driver prints end.
  2. The remaining slots go out of scope in reverse order of creation, the way local variables die at a closing brace. A slot is created by a make, copy, or move that succeeds.
  3. Last, the driver prints leaked none, or leaked followed by the number of every array that was allocated and never freed.

Lines that point at bugs

A correct class never produces these lines:

LineMeaning
a second delete[] #kthe array was freed twice (the driver never returns memory to the system, so this does not crash)
print s #k freed [...]the buffer still points at a freed array, which reads as -1 in every element
elements reading 1431655765a new array the class has not written yet
delete #kan array freed with plain delete
new #ka heap allocation that is not an array
print s null size ndata() is null while size() is not 0
set s i out of rangesize() is too small for the index

Part 1: Own and copy

Implement the constructor, the destructor, the copy constructor, copy assignment, and swap. Part 1 tests never use move or moveassign, so the two move members can stay empty for now.

Tests 1–5 cover this part.

Part 2: Move without allocating

A move hands an array to a new owner without copying it. Two members are new:

MemberContractCalled by
PriceBuffer(PriceBuffer&& other) noexceptTakes other's array and size and leaves other empty (size 0, nullptr). Allocates and frees nothing.move d s
PriceBuffer& operator=(PriceBuffer&& other) noexceptFrees *this's array, if any, takes other's array and size, and leaves other empty. Allocates nothing.moveassign d s
  • A moved-from buffer is empty and fully usable: it can be printed, copied (which allocates nothing), assigned to, moved into again, and destroyed.
  • Move-assigning a buffer to itself is outside the contract, and no test does it.
CommandWhat the driver runsPrints
move d sPriceBuffer d(std::move(s));events
moveassign d sd = std::move(s);events

Tests 6–9 cover this part.

Example
Input
8
make a 3
set a 0 18950
set a 2 18960
copy b a
set b 1 18955
assign a b
print a
print b
Output
new[] #1 size 3
new[] #2 size 3
new[] #3 size 3
delete[] #1
print a #3 [18950 18955 18960]
print b #2 [18950 18955 18960]
end
delete[] #2
delete[] #3
leaked none
Explanation

make a 3 allocates array #1 of three zeros, and the two set commands fill two of them. copy b a is a deep copy into a new array #2, so set b 1 18955 changes b only.

assign a b allocates array #3 and copies b's values into it before it frees a's old array #1. The print lines show that a and b hold the same values in different arrays.

At the end, b goes out of scope first because it was created after a.