Terminology (5)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- RAII
- Resource acquisition is initialization: a constructor acquires a resource and the destructor releases it when the object’s lifetime ends.
- Rule of three / five
- A class that defines a destructor, copy constructor or copy assignment usually needs all three; with moves, all five.
- Rule of zero
- Hold resources in members that manage themselves, so the class needs none of the five.
- Moved-from object
- The source of a move: valid but unspecified for library types; for your own owners, typically owning nothing.
- Strong exception guarantee
- An operation either succeeds or leaves its protected value unchanged. In this lab that value includes the target upload’s name and owned slot contents.
Object lifetime and resource ownership
An object’s lifetime runs from its construction to its destruction. RAII ties a resource such as an allocated array or open file to that lifetime: acquiring it establishes an owner, and normal destruction releases it. The object’s storage and the resource it owns can have different lifetimes.
Copy construction creates another object from an existing one; assignment changes an object that already exists. A move can transfer ownership instead of duplicating the resource. The rule of five asks these operations and the destructor to express one coherent ownership policy. Self-managing members can supply that policy through their own operations: the rule of zero.
01Copies
What does the implicit copy of an owner copy?
The upload queue must retain a failed file for retry while continuing to accept new files. Its Upload class exclusively owns one storage slot, but an implicit copy gives two objects the same slot number. First establish independent retry ownership, then transfer ownership during growth without duplicating large files. A replacement adds another requirement: failure must leave the previous queued file intact.
Buffer allocates an array in its constructor and deletes it in its destructor. It declares no copy constructor, so the compiler generates one that copies each member, including the pointer.
This reduced filename owner isolates pointer copying from the upload queue’s storage policy. Its inner-scope copy frees the array before the original is read. The recorded undefined-behavior outcome diagnoses ownership; it is not a portable test to reproduce.
#include <cstdio>
#include <cstring>
/// Owns a heap copy of a file name.
struct Buffer {
char *data;
explicit Buffer(const char *text) : data(new char[std::strlen(text) + 1]) {
std::strcpy(data, text);
}
~Buffer() {
delete[] data;
}
};
int main() {
Buffer original("photo.jpg");
{
Buffer copy = original; // the implicit copy copies the pointer
std::printf("copy: %s\n", copy.data);
std::fflush(stdout);
} // copy's destructor deletes the array
std::printf("original after the copy is gone: %s\n", original.data);
std::fflush(stdout);
} // original's destructor deletes it again
g++ -std=c++23 -Wall -Wextra main.cpp -o main && ./main
The quoted outputs are historical observations from GCC 12.2/libstdc++ with glibc, not new runs. shallow.cpp deliberately has undefined behavior: its garbage bytes/abort are one observation, not a portable test expectation. The lab instead uses authored integer storage slots with explicit guard failures; it does not perform real uploads or manage native file descriptors.
02Moves
When does a vector move its elements?
Once retry copies are independent, inspect growth: a full vector needs new storage for its elements. A resource handover can avoid storage::copy, but a throwing move could have changed earlier source elements before failure. The recorded implementation uses a copy path for the potentially throwing mover and a transfer path for the noexcept mover.
The reduced types below omit upload storage and count their copy/move constructor calls during growth to 100 elements. Only one move constructor is marked noexcept; the experiment isolates the library’s transfer choice, not upload throughput.
#include <cstdio>
#include <vector>
int copies = 0, moves = 0;
struct MaybeThrows {
int id;
explicit MaybeThrows(int id) : id(id) {}
MaybeThrows(const MaybeThrows &other) : id(other.id) {
++copies;
}
MaybeThrows(MaybeThrows &&other) : id(other.id) {
++moves;
}
};
struct NeverThrows {
int id;
explicit NeverThrows(int id) : id(id) {}
NeverThrows(const NeverThrows &other) : id(other.id) {
++copies;
}
NeverThrows(NeverThrows &&other) noexcept : id(other.id) {
++moves;
}
};
template <typename T>
void grow(const char *name) {
copies = moves = 0;
std::vector<T> items;
for (int i = 0; i < 100; ++i)
items.emplace_back(i);
std::printf("%s: %d copies, %d moves\n", name, copies, moves);
}
int main() {
grow<MaybeThrows>("move constructor without noexcept");
grow<NeverThrows>("move constructor with noexcept");
}
03Assignment
What if the copy fails halfway through an assignment?
Assignment replaces a resource the object already owns. A natural first version releases the old resource and then copies the new one. If the copy throws, the object has already released what it owned but still refers to it.
The same order also breaks a = a: the object releases the very resource it is about to copy.
| Order | If the copy throws | a = a |
|---|---|---|
| Release, then copy | The object names a released resource | Copies a resource it just released |
| Copy, then release (or copy-and-swap) | The object keeps its old value | Makes a copy, then releases the old one |
04Practice
Fix the upload queue
The lab is an upload queue with authored integer storage slots. Easy first establishes independent ownership using copyable files of 0–1000 bytes. Medium admits larger files: growth must transfer their existing slots, while an explicit retry over 1000 bytes is rejected. Hard adds replacement and rejection safety. Closing/reading an invalid slot triggers an explicit guard failure; the report counts storage::copy calls, not native allocation or all C++ copy operations.
The upload queue
Give each copy its own slot, move uploads as the queue grows, then make replace safe when a copy fails.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?