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
PriceBufferat 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, sostd::copy,std::size_t,std::swap,std::exchange, andstd::moveare available.#includeany 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
PriceBufferholds a pointerdata_and a lengthsize_. - A buffer of size 0 is empty: its pointer is
nullptrand it owns no array. - Every other buffer owns exactly one array of
size_ints, allocated withnew int[n]and freed withdelete[]. An array fromnew[]must be freed withdelete[], never plaindelete. - No member allocates an array of length 0, and no member uses the heap in any other way.
| Member | Contract | Called 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) noexcept | Exchanges 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) const | Element i. Already written. | set, print |
std::size_t size() const noexcept | The number of elements. Already written. | set, print |
const int* data() const noexcept | The array, or nullptr when empty. Already written. | print |
The driver checks at compile time that:
PriceBuffercan be copy constructed and copy assigned;- both move operations and
swaparenoexcept; - the
std::size_tconstructor isexplicit, and the twooperator[]overloads returnint&andconst 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:
- It allocates the new array and copies
other's values into it before it changes*thisor frees anything. - Only then does
*thistake the new array. - 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 thendelete[](the second only if*thisheld an array). - A copy assignment from an empty buffer allocates nothing, frees the old array, and leaves
*thisempty.
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, andmovename an absent target slot; every other slot a command names is present.assign,moveassign, andswapname two different slots.setuses an index below the buffer's size, and every value fits in anint.
| Command | What the driver runs | Prints |
|---|---|---|
make s n | PriceBuffer s(n); | events |
set s i v | s[i] = v; | nothing |
print s | Reads 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 s | PriceBuffer d(s); | events |
assign d s | d = s; | events |
selfassign s | s = s; | events |
swap a b | a.swap(b); | events |
drop s | s goes out of scope: its destructor runs and the slot becomes absent. | events |
fail | The 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 happens | Printed line |
|---|---|
a PriceBuffer member allocates an array of n ints | new[] #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 fail | new[] size n fails, with no number, then std::bad_alloc is thrown |
- In a
printline,#knames the array thatdata()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
failwaiting for the next allocation:selfassign,swap,set,print,drop, amakeof size 0, acopyorassignfrom an empty buffer, and in Part 2moveandmoveassign. - When the exception reaches the driver, it prints
caught bad_allocand moves on to the next command. Amakeorcopythat throws leaves its target slot absent; anassignthat throws leaves both buffers as they were.
End of input
- The driver prints
end. - 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, ormovethat succeeds. - Last, the driver prints
leaked none, orleakedfollowed by the number of every array that was allocated and never freed.
Lines that point at bugs
A correct class never produces these lines:
| Line | Meaning |
|---|---|
a second delete[] #k | the 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 1431655765 | a new array the class has not written yet |
delete #k | an array freed with plain delete |
new #k | a heap allocation that is not an array |
print s null size n | data() is null while size() is not 0 |
set s i out of range | size() 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:
| Member | Contract | Called by |
|---|---|---|
PriceBuffer(PriceBuffer&& other) noexcept | Takes other's array and size and leaves other empty (size 0, nullptr). Allocates and frees nothing. | move d s |
PriceBuffer& operator=(PriceBuffer&& other) noexcept | Frees *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.
| Command | What the driver runs | Prints |
|---|---|---|
move d s | PriceBuffer d(std::move(s)); | events |
moveassign d s | d = std::move(s); | events |
Tests 6–9 cover this part.
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
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
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.