C++ Pointers
Use an address to select a live object without pretending that a non-owning pointer manages its lifetime.
How it works
A raw pointer can represent a borrowed object or no object through nullptr. Address-of obtains an object pointer and dereference accesses its target only when that pointer is valid. A non-null pointer can still dangle after its target is destroyed or moved by a container reallocation. Prefer a reference for a required borrowed object and a pointer for an optional selection when that matches the API. Neither form supplies ownership tracking or automatic bounds validation.
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 borrowing-pointers.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.
Example
#include <iostream>
int main() {
int west{4};
int east{7};
int *selected = &west;
*selected += 1;
selected = &east;
std::cout << "West: " << west << "; selected: " << *selected << '\n';
selected = nullptr;
std::cout << "No selection: " << (selected == nullptr) << '\n';
}
Expected result
West: 5; selected: 7
No selection: 1
Both candidate ints remain alive for every access. Assignment through the pointer changes the selected int, while assignment to the pointer selects another target. Numeric addresses are deliberately excluded from expected output because they vary. A pointer-to-pointer is needed only when a function must replace a caller’s raw pointer object; returning a suitable value often makes that interface simpler.
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.