C++ Quiz
Predict a value copy and a reference update, then explain which owner keeps each result alive.
Your brief
Before opening the answer, decide what a copied vector contains after the original is updated, what a reference sees and whether a reserved capacity is a valid element count. Then explain why an invalid iterator or a view of a destroyed local object does not have a reliable output to memorise. A useful C++ knowledge check asks for the lifetime and precondition behind a result, not a compiler-specific accident. This fixture uses only well-defined operations and observable independent values.
Run it locally
Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror quiz.cpp -o lessonOn Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.
Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.
Worked solution
Show the worked solution
#include <iostream>
#include <vector>
int main() {
std::vector<int> original{2, 4};
auto copied = original;
int& alias = original.at(0);
alias = 9;
std::cout << "Original: " << original[0] << "; copy: " << copied[0] << '\n';
std::cout << "Elements: " << original.size() << '\n';
}
Expected result
Original: 9; copy: 2
Elements: 2
The vector copy owns separate element storage. The reference aliases one live element in original, so updating it changes that vector only. No operation reallocates original while alias is used. reserve could later invalidate this reference if it caused a reallocation; the current statement sequence intentionally avoids that risk.
Extend and test
Explain what changes if copied is declared as auto& instead. Then identify one later vector operation that could invalidate alias and state when that happens.
Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.