C++ Foundations
Core types, control flow, functions, arrays, strings, ownership and lifetimes, expected errors, separate build stages and tests. Introductory c++20 subset only.
Audience: Learners who have practiced basic control flow and can invoke an installed compiler.
Practice: 5 to 7 hours.
Runtime and boundaries: Export one entry source and any companion files to a fresh practice folder. Compile with clang++ -std=c++20 -Wall -Wextra -Wpedantic -Werror "C++ 01 Values.cpp" -o "Atlas example", then run ./"Atlas example" only after compilation succeeds. These are recorded installed tools; do not run a package manager. The browser exports source only and never invokes the compiler. Use separate fresh directories to avoid executing stale output. Exact test environment: Apple Clang 21.0.0 (clang-2100.3.34.2); arm64 macOS 27.0.1; libc++ 220106.
Lessons
Choose C++20 deliberately
Compile .cpp files with clang++ -std=c++20 so the driver links the C++ library. The installed Apple Clang 21.0.0 and libc++ 220106 support the subset actually tested here. Enabling a standard mode does not prove every feature is implemented; modules, ranges pipelines, coroutines and platform-specific APIs are outside this pack.
Prefer owning values
Use std::string, std::array and std::vector to express ownership. Copying a value container copies its values rather than simply sharing a C pointer. A vector can reallocate and invalidate pointers or views; the examples do not retain such views across mutation.
References and views borrow
A reference, string_view or span does not own the referred object and does not extend its lifetime. Keep the owner alive and storage stable for all uses. span carries a bound but C++20 operator[] is not a bounds-checked operation; range iteration or a deliberately checked access is often clearer.
Functions express results
An optional result represents expected absence without inventing a sentinel or exposing an output pointer. Check engagement before dereferencing. const restricts mutation through the given access path; it is not a general ownership or thread-safety guarantee.
RAII and unique ownership
Resource Acquisition Is Initialization associates a resource with an object lifetime. Containers and unique_ptr release owned storage automatically at normal destruction. std::move enables move operations; it does not itself transfer or destroy anything. This unique_ptr move empties its source, while other moved-from types have different contracts.
Errors remain observable
Use an optional for expected missing results, error codes where an API defines them, and exceptions where appropriate. Catch the expected exception by reference. vector::at throws on an invalid index; accessing an unchecked invalid index would be undefined behavior and is never demonstrated here.
Build and test separately
Header definitions, object compilation and linking have distinct roles. constexpr permits compile-time evaluation when its conditions are met; static_assert demands a compile-time truth. Runtime assert and stdout checks are separate evidence. Negative compiler fixtures are intentionally invalid and are not counted as successfully executing programs.
Practice within limits
The examples avoid raw owning new/delete, unchecked C string operations and arbitrary external input. Lifetime rules still matter in C++. Sanitizer success is limited to the executed paths and cannot certify safety. No deployment, concurrency, ABI compatibility, allocation-failure injection or full standard conformance is claimed.
Reference cards
Initialization: int count{3}
Braces reject many narrowing conversions.
Owning text: std::string
Owns character storage with value semantics.
Fixed array: std::array<T, N>
Owns a fixed number of elements.
Dynamic sequence: std::vector<T>
Owns elements; mutation may invalidate views.
Borrowed range: std::span<const T>
C++20 view, with length but no ownership.
Borrowed text: std::string_view
Does not extend owner lifetime or require a terminator.
Optional: std::optional<T> / std::nullopt
A result value or explicit absence.
Unique owner: std::make_unique<T>(...)
Creates storage managed by unique_ptr.
Move: std::move(value)
Enables move selection; follow type-specific postconditions.
Checked access: values.at(index)
Throws out_of_range if invalid.
Exception: catch (const std::out_of_range&)
Handle the expected failure type.
Parsing: std::from_chars(first, last, value)
Integer conversion reports end pointer and error code.
Compile-time test: static_assert(expression)
Must be a constant expression evaluating true.
Runtime test: assert(expression)
Executes only when enabled; not input validation.
Cleanup: ~Type()
Destructor runs at normal object destruction.
Driver: clang++ -std=c++20
Pins language mode and links the C++ library.
Supporting configuration: Build instructions.txt
Export one entry source and any companion files to a fresh practice folder. Compile with clang++ -std=c++20 -Wall -Wextra -Wpedantic -Werror "C++ 01 Values.cpp" -o "Atlas example", then run ./"Atlas example" only after compilation succeeds. These are recorded installed tools; do not run a package manager. The browser exports source only and never invokes the compiler. Use separate fresh directories to avoid executing stale output.
Examples and practice
Code below is reading material, not an execution console. Download the edition for the complete example files and companion modules.
C++ 01 - Values and initialization
std::string owns its character storage. Braced initialization rejects many narrowing conversions. Stream output does not use C printf format strings.
#include <iostream>
#include <string>
int main() {
const std::string title{"Read"};
const int minutes{25};
const bool ready{minutes > 0};
std::cout << title << ": " << minutes << '\n';
std::cout << std::boolalpha << ready << '\n';
return 0;
}
Expected:
Read: 25 true
Intentionally invalid C++: expected compiler diagnostic containing cannot be narrowed. Expected rejection; not a successful program. No runtime execution follows rejection.
int main() { int n{1.5}; return n; }C++ 02 - Iterate over a value collection
Range iteration avoids manually maintaining an index for this operation. The fixed small values keep integer arithmetic in range; containers do not make signed overflow defined.
#include <array>
#include <iostream>
int main() {
const std::array<int, 4> values{1, 2, 3, 4};
int total{0};
for (const int value : values) {
if (value % 2 == 0) { total += value; }
}
std::cout << "Even total: " << total << '\n';
return 0;
}
Expected:
Even total: 6
C++ 03 - Return an optional result
optional represents a value or absence without an output pointer. Check that a value exists before dereferencing. This C++20 example does not use later optional monadic or range APIs.
#include <iostream>
#include <optional>
std::optional<int> double_minutes(int value) {
if (value < 0 || value > 120) { return std::nullopt; }
return value * 2;
}
int main() {
const auto good = double_minutes(20);
if (good) { std::cout << "Double: " << *good << '\n'; }
std::cout << "Invalid rejected: " << std::boolalpha
<< !double_minutes(-1).has_value() << '\n';
return 0;
}
Expected:
Double: 40 Invalid rejected: true
C++ 04 - Owning arrays and borrowed spans
std::array owns its elements; C++20 std::span borrows a contiguous sequence and carries its length. A span does not extend lifetime and C++20 operator[] does not promise bounds checking. This loop consumes the span while the owner is alive. Every intermediate sum and the final sum must fit int; this is the arithmetic precondition, independent of span bounds.
#include <array>
#include <iostream>
#include <span>
int total(std::span<const int> values) {
int sum{0};
for (const int value : values) { sum += value; }
return sum;
}
int main() {
const std::array<int, 3> values{10, 20, 30};
std::cout << "Total: " << total(values) << '\n';
std::cout << "Empty: " << total(std::span<const int>{}) << '\n';
return 0;
}
Expected:
Total: 60 Empty: 0
C++ 05 - Strings and borrowed views
string_view borrows; string owns. The owner remains alive and unmodified for every use of view. A view need not be zero-terminated. Byte counts are not general Unicode character counts.
#include <iostream>
#include <string>
#include <string_view>
int main() {
const std::string label{"Read:20"};
const std::string_view view{label};
std::cout << view.substr(0, 4) << '\n';
std::cout << "Bytes: " << label.size() << '\n';
const std::string copy{view};
std::cout << "Copy: " << copy << '\n';
return 0;
}
Expected:
Read Bytes: 7 Copy: Read:20
C++ 06 - Value semantics
The std::string member has value semantics, so changing the copy does not change the original. Contrast C struct copying a pointer member: that copies the address rather than the referenced characters.
#include <iostream>
#include <string>
struct Task { std::string title; int minutes; };
int main() {
const Task original{"Read", 20};
Task copy = original;
copy.title = "Code";
std::cout << original.title << ": " << original.minutes << '\n';
std::cout << copy.title << ": " << copy.minutes << '\n';
return 0;
}
Expected:
Read: 20 Code: 20
C++ 07 - Transfer unique ownership
unique_ptr owns one allocation and releases it automatically at scope exit. Moving transfers ownership; the source unique_ptr becomes empty. Do not generalize that empty-state guarantee to every moved-from type. Allocation failure is not fault-injected.
#include <iostream>
#include <memory>
#include <utility>
int main() {
auto first = std::make_unique<int>(42);
auto second = std::move(first);
std::cout << "First empty: " << std::boolalpha << !first << '\n';
std::cout << "Value: " << *second << '\n';
return 0;
}
Expected:
First empty: true Value: 42
Intentionally invalid C++: expected compiler diagnostic containing implicitly-deleted copy constructor. Expected rejection; not a successful program. No runtime execution follows rejection.
#include <memory>
int main() { auto a = std::make_unique<int>(1); auto b = a; }C++ 08 - Recover from an expected exception
vector::at checks the index and throws out_of_range. vector::operator[] does not provide that guarantee in the C++20 contract. Catch the expected type by reference; no out-of-bounds access is performed.
#include <iostream>
#include <stdexcept>
#include <vector>
int main() {
const std::vector<int> values{10, 20};
std::cout << "First: " << values.at(0) << '\n';
try {
std::cout << values.at(9) << '\n';
} catch (const std::out_of_range&) {
std::cout << "Index rejected\n";
}
return 0;
}
Expected:
First: 10 Index rejected
C++ 09 - A header and compile-time contract
The inline constexpr definition is visible in the header. static_assert is checked during compilation; the printed output is separate runtime evidence. This is ordinary header inclusion, not C++20 modules.
#include <iostream>
#include "Atlas math.hpp"
static_assert(atlas_double(6) == 12);
int main() {
std::cout << "Double: " << atlas_double(6) << '\n';
return 0;
}
Expected:
Double: 12
Companion file: Atlas math.hpp
#ifndef ATLAS_MATH_HPP
#define ATLAS_MATH_HPP
// Caller supplies 0..120.
inline constexpr int atlas_double(int value) { return value * 2; }
#endif
Intentionally invalid C++: expected compiler diagnostic containing static assertion failed. Expected rejection; not a successful program. No runtime execution follows rejection.
static_assert(2 + 2 == 5, "deliberate failure");
int main() {}C++ exercise A - An optional average
The span borrows valid storage, while optional owns a result value or represents absence. The function validates at most ten minute values and never divides by zero.
#include <array>
#include <iostream>
#include <optional>
#include <span>
std::optional<double> average(std::span<const int> values) {
if (values.empty() || values.size() > 10) { return std::nullopt; }
int sum{0};
for (const int n : values) {
if (n < 0 || n > 120) { return std::nullopt; }
sum += n;
}
return static_cast<double>(sum) / static_cast<double>(values.size());
}
int main() {
const std::array<int, 2> values{10, 20};
const auto result = average(values);
if (!result) { return 1; }
std::cout << "Average: " << *result << '\n';
std::cout << "Empty rejected: " << std::boolalpha
<< !average(std::span<const int>{}).has_value() << '\n';
return 0;
}
Expected:
Average: 15 Empty rejected: true
Practice: Return an optional average over at most ten values in 0..120. Demonstrate empty input without dereferencing an empty optional.
C++ exercise B - Parse a complete number
Integer from_chars reports an error code and end pointer without throwing. Unlike strtol, this conversion does not skip leading whitespace or accept a leading plus sign. The policy requires complete consumption and values in 0..120.
#include <charconv>
#include <initializer_list>
#include <iostream>
#include <optional>
#include <string_view>
#include <system_error>
std::optional<int> minutes(std::string_view text) {
if (text.empty()) { return std::nullopt; }
int value{0};
const auto result = std::from_chars(text.data(), text.data() + text.size(), value);
if (result.ec != std::errc{} || result.ptr != text.data() + text.size() ||
value < 0 || value > 120) { return std::nullopt; }
return value;
}
int main() {
for (const auto text : {"20", "x", "121", "15tail"}) {
const auto result = minutes(text);
if (result) { std::cout << *result << '\n'; }
else { std::cout << "invalid\n"; }
}
return 0;
}
Expected:
20 invalid invalid invalid
Practice: Parse the entire supplied view, reject errors and trailing content, and keep range policy separate from conversion.
C++ exercise C - Test a lifetime boundary
A destructor runs at this ordinary scope exit. The referenced count outlives the Counter, and copying is disabled to preserve this toy invariant. This does not demonstrate cleanup after forced termination, leaks, concurrency or every exceptional path.
#include <cassert>
#include <iostream>
struct Counter {
int& live;
explicit Counter(int& count) : live(count) { ++live; }
~Counter() { --live; }
Counter(const Counter&) = delete;
Counter& operator=(const Counter&) = delete;
};
int main() {
int live{0};
{
Counter owner{live};
assert(live == 1);
std::cout << "Inside: " << live << '\n';
}
assert(live == 0);
std::cout << "After scope: " << live << '\n';
return 0;
}
Expected:
Inside: 1 After scope: 0
Intentionally invalid C++: expected compiler diagnostic containing const-qualified. Expected rejection; not a successful program. No runtime execution follows rejection.
int main() { const int n = 1; n = 2; return n; }Practice: Track one automatic object with a constructor and destructor. Assert the live count inside and after its scope; ensure the count outlives the object.
Prompt templates
These are editable planning prompts in the downloadable workbench; they do not contact an AI service here.
Build a bounded example
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Return complete source and companion files, exact compiler flags, expected output and resource ownership. Do not claim tests ran without evidence.Diagnose a build or runtime failure
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Separate compiler, linker and runtime symptoms. Show a minimal correction and a regression check. Do not claim tests ran without evidence.Design boundary tests
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Cover empty, boundary and rejected input. Separate static rejection fixtures from successful programs and actual execution. Do not claim tests ran without evidence.Refactor with clear ownership
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Preserve output and explain lifetimes, bounds and ownership before and after the change. Do not claim tests ran without evidence.Document a contract
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. State pointer/view preconditions, ranges, outputs, failure behavior, compiler mode and unsupported cases. Do not claim tests ran without evidence.Review lifetime and arithmetic risks
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Check dangling views, invalid bounds, format mismatches, unchecked allocation and integer overflow. Do not introduce deliberate undefined behavior. Do not claim tests ran without evidence.Further reading
- Clang compiler user manual — Compiler driver, standard modes and diagnostics; upstream documentation is not an Apple feature guarantee.
- Clang C++ implementation status — C++20 mode and partial feature coverage; actual subset tested locally.
- libc++ C++20 implementation status — Library feature status; Apple-shipped version verified locally.
- C++ Core Guidelines — Ownership, lifetimes and resource management guidance, not normative standard text.
- C++ working draft: object lifetime — Living working draft; lifetime concepts only, not a C++20 publication.
- C++ working draft: unique ownership — Living draft; elementary unique_ptr ownership and move semantics, excluding later additions.
- C++ working draft: span — Living draft; borrowing and length concepts; later span APIs excluded from C++20 exercises.
- C++ working draft: optional — Living draft; engaged value and absence only; later APIs excluded.
- Clang AddressSanitizer — Instrumented checking of some memory errors on executed paths; not safety proof.
- Clang UndefinedBehaviorSanitizer — Checks for selected undefined behavior; coverage is incomplete.
- C++ working draft: from_chars — Living draft; integer error code, end-pointer and no-throw concepts available in the exercised C++20 subset. Later constexpr additions are not used.
Download the offline edition
Complete Atlas 0.11.0 ZIP (6,079,970 bytes) · 411-page guide and catalogue PDF · Versioned source JSON
Unzip the edition and open Programming and Scripting Atlas.html, Web Foundations.html, Python Foundations.html, SQL Foundations.html, Shell Foundations.html, TypeScript Foundations.html Data Formats Foundations.html, C Foundations.html C++ Foundations.html, Ruby Foundations.html, Perl Foundations.html, Swift Foundations.html, Makefile Foundations.html, awk Foundations.html, sed Foundations.html, jq Foundations.html, XSLT 1.0 Foundations.html, Tcl Foundations.html, Expect Foundations.html or Objective-C Foundations.html locally. The original interactive workbenches retain their offline prompt-building, local presets and export controls. Read the included README before running examples yourself. The workbench does not execute pasted code or call an AI service; prompt text is for you to inspect and use separately.
Version 0.11.0 is pinned here. The other 257 registry entries remain planned; this edition does not claim complete language coverage.
Evidence and limits
Objective-C adds 12 accepted native programs, four separate compiler or warning-policy rejections, 120 root checks and 147 independent native checks. Two rejection fixtures are warnings promoted by -Werror; they are not intrinsic syntax failures. No rejected fixture was executed. Tests dated 26 October 2026 used Apple Clang 21.0.0, ARC, C17 base mode, macOS SDK 27.0 headers and system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. This is introductory macOS/Foundation coverage, not iOS, GNUstep, Objective-C++, UI, concurrency or cross-platform coverage. No sanitizers, leak detector, race analysis, allocation/disk-full/permission fault injection or asynchronous timing tests were run. Trusted authored fixtures and process bounds do not establish an arbitrary-code sandbox.
The pinned Atlas 0.11.0 evidence records 607 browser checks, 55 Python harness checks plus four unittest methods, 74 SQL checks, 515 shell checks across 71 runs, 99 TypeScript checks, 51 Data Formats checks, 119 C checks, 116 C++ checks, 97 Ruby checks, 97 Perl checks, 105 Swift harness checks and 97 Makefile harness checks, 145 awk checks, 145 sed checks, 161 jq checks, 157 XSLT checks, 150 Tcl checks and 161 Expect checks. These are separate measures. Tcl and Expect tests are dated 26 October 2026 on installed Tcl 8.5.9 / Expect 5.45 with Tcl 8.5.9 on macOS arm64. These old versions are recorded teaching evidence, not deployment recommendations. Tcl has 12 accepted programs and Expect has 12 accepted controllers; each has four expected evaluation failures, not static compilation passes. Tcl has nine scenarios, five expected nonzero; Expect has seven scenarios, four expected nonzero. Expect default controllers invoke 15 toy children, including two expected child failures; one scenario also expects a failed child. Controller success does not mean every child succeeds. The authoring release records 100 owned-runner regression checks and 109 independent runner checks separately. Only authored fixtures and retained native child handles are covered. Cooperative cleanup requires event-loop progress; outer-timeout child cleanup remains uncertain without complete wait receipts. The retired PID-inspection branch was not retried. No sign-ins, secrets, network or external application control are taught or tested by this pack. awk and sed are text-processing languages; their examples use fixed authored ASCII input and the C locale with installed awk 20200816 and macOS sed on one platform. jq and XSLT each have 12 accepted examples and four separately rejected programs. jq has 21 scenarios, including five contract errors and one no-result status; XSLT has 20 scenarios, including five terminating messages and one CLI parameter rejection. Expected nonzero outcomes are not successful programs. Tests dated 26 October 2026 used jq 1.7.1-apple and XSLT 1.0 with libxslt 1.1.35/libxml2 2.9.13, fixed trusted programs and tiny authored inputs in the C locale on macOS arm64. These old installed XML libraries are recorded learning environments, not recommendations for untrusted-document processing. No imports, external documents, DTDs, custom/external entities, extension functions or generated source are covered. Command flags and bounds are not a complete sandbox. Standalone XPath remains planned; supporting XPath 1.0 expressions are limited to these XSLT examples. These tests do not establish GNU-tool equivalence, Unicode behavior, arbitrary-script safety or cross-platform portability. Swift has 12 accepted programs and four expected static rejections; Makefile has 12 accepted default targets, four expected parser rejections, eight additional scenarios and one expected recipe failure. Makefile is build scripting, not a general-purpose language. The Swift and Makefile test execution dates remain 25 October 2026. awk and sed tests are dated 26 October 2026. Delivery verification does not replace or refresh test execution dates. TypeScript includes 12 accepted programs executed as JavaScript and nine intentionally invalid cases correctly rejected. Each C/C++ pack has 12 accepted programs run normally and with AddressSanitizer/UndefinedBehaviorSanitizer, plus four expected compiler rejections that are never executed. Ruby and Perl each have 12 syntax-accepted programs executed and four expected syntax rejections; rejected cases are not successful programs. Syntax checks may execute compile-time code and are not arbitrary-code sandboxes. Sanitizer results cover executed paths only; leak detection and allocation-failure injection were not tested and memory safety is not proved.
Tested environments are Chrome 155, CPython 3.9.6, SQLite CLI 3.54.0, macOS sh/Bash 3.2.57/Zsh 5.9, TypeScript 6.0.3, Node 24.18.0 Apple Clang 21.0.0, Ruby 2.6.10p210 and Perl 5.34.1, Apple Swift 6.4 in Swift 6 mode and GNU Make 3.81 on one arm64 macOS host. C uses a C17 subset; C++ uses a C++20 subset with libc++ 220106. Python 3.9.6 is unsupported upstream. Ruby 2.6 is end-of-life upstream; the recorded installed interpreter is not a recommended modern runtime. Data Formats uses installed Tomli 1.0.3 through a private fallback; the Python tomllib branch was not run. No new-installation recommendation, complete language/format conformance, schema certification, hardened untrusted XML parsing or general-purpose execution sandbox is established. Other platforms, browsers and screen readers remain unverified. The 145 official references belong to the saved Atlas review, not fresh website-time verification.