L5 · LanguagesProgramming Languages 101 · part 1 of 6

C++ 101: The Language That Trusts You Completely

C++ gives you control over every byte of memory, and its modern features do most of the cleanup for you. Values, references, RAII, classes, templates and the standard library, with the reason behind each one.

Takumi Yamada
· 11 min read · 3 references
cppc++programming-languagesmemoryperformance
The C++ logo: a blue hexagon with a white letter C and two small plus signs.
The C++ logo, used by the Standard C++ Foundation. C++ is defined by an ISO standard, and since 2011 a new version has come out every three years: C++11, C++14, C++17, C++20 and C++23.Logo: Jeremy Kratz for the Standard C++ Foundation, public domain (trademark), via Wikimedia Commons (original). Changes: placed on a background.

C++ began in 1979 as "C with Classes". Bjarne Stroustrup wanted to keep the speed of C and add the classes of Simula, an older language made for simulations. Today C++ runs inside web browsers, game engines, , trading systems, and most of the machine learning libraries that Python calls.

Bjarne Stroustrup, a man with grey hair and glasses, wearing a dark shirt.
Bjarne Stroustrup, who created C++, in 2013.Photo: Victor Zavyalov for ICPCNews, CC BY 2.0, via Wikimedia Commons (original). Changes: cropped.

One design rule has held the whole time. It's called the zero-overhead principle.

You don't pay for what you don't use, and what you do use, you could not hand code any faster.

This rule explains both sides of the language's reputation. C++ is fast because it adds no hidden work. People call it dangerous for the same reason, because it adds no hidden checks either. The language assumes you know what you are doing, and it doesn't stop you.

The C++ many of us learned in school was the 1990s style, with long chains of classes inheriting from each other and memory freed by hand. Most of that is outdated now. This post covers modern C++, the way it's written today, with the reason behind each piece.

Hello, compilation

#include <iostream>

int main() {
    std::cout << "hello, world\n";
    return 0;
}

To compile it, run g++ -std=c++20 -Wall hello.cpp -o hello. The -std=c++20 part picks the 2020 version of the language, and -Wall turns on most warnings.

C++ builds a program in two steps, and you deal with both of them directly. First the turns each .cpp file into an object file, one file at a time. Then the linker joins the object files into one program.

The #include line copies the text of another file into yours before compiling. That's why C++ has header files (.h). They hold the declarations that several .cpp files need. In a large project there are too many of these files to manage by hand, so projects use a build system such as CMake. C++20 added modules to replace #include, but most code you read will use #include for years to come.

shapes.h#include pastesits text into botha.cppcompilea.ob.cppcompileb.oLINKERhelloone executable
The build of a program with two source files. The file names are examples.

std:: is the namespace of the . A namespace is a prefix that keeps the library's names apart from yours. Tutorials often write using namespace std; so that they can leave the prefix out. That's fine in a small test file. In a header it causes problems, because it pulls thousands of names into every file that includes the header.

Values, and where they live

The most important idea in C++ is that every variable is an object at a real address in memory, and you decide where that memory is.

int  x = 42;            // stack: automatic, freed when the scope ends
int* p = new int(42);   // heap: manual, lives until you delete it

x lives on the , and it's freed automatically when the block it's in ends. The 42 that p points to lives on the , and it stays there until you free it yourself with delete.

STACKx42p0x5f20HEAP42freed automaticallywhen the scope endsfreed only by delete pforget it and it leaks,do it twice and it's undefined behaviour
Where those two lines put things.

A function can receive an argument in three ways.

void byValue(std::string s);            // gets its own copy
void byRef(std::string& s);             // uses the caller's string, can change it
void byConstRef(const std::string& s);  // uses the caller's string, read only

Passing by value makes a copy. If the argument is a vector of a million numbers, all million are copied. Passing by reference doesn't copy anything. The function gets an alias, which is a second name for the caller's own string. Adding const means the function can read the string but not change it.

So the usual rule is this. Pass small types such as int and double by value, because copying them costs almost nothing. Pass anything larger as const T&.

"hello"the caller's stringcopied"hello"byValue: its own copychanging it changesonly the copysbyRef: an aliascan changethe originalsbyConstRef: an aliascan onlyread it
One string passed three ways. Only the first makes a copy.

A reference, like std::string& s, is always connected to one object. It can't be empty, and it can't be switched to a different object later. A pointer, like std::string* p, holds an address. It can be , which means it points to nothing, and it can be changed to point somewhere else. Use a reference by default. Use a only when the object might not exist, or when you need to point at a different object later.

The stack and heap diagram above mentions undefined behaviour, which is the best known danger in C++. It means the language makes no promise at all about what happens. Reading past the end of a vector is one example.

std::vector<int> v = {1, 2, 3};
int a = v[10];     // undefined behaviour: no check, anything can happen
int b = v.at(10);  // checked: throws std::out_of_range

v[10] might crash, return a random number, or seem to work for a long time. The compiler assumes your program never does this, and it builds the program on that assumption. Using memory after it was freed and overflowing a signed integer are undefined behaviour too. This is the cost of the zero-overhead principle. C++ doesn't add a check unless you ask for one, the way at() does.

RAII: the best idea in the language

This section covers the idea that makes the rest of modern C++ work.

When a block of code ends, the objects created inside it are destroyed right away, in a known order. Destroying an object runs a special function called its destructor. C++ uses this to clean up every kind of resource automatically, such as an open file, a lock or a piece of memory.

{
    std::ifstream file("config.json");   // constructor opens the file
    std::lock_guard lock(mutex);         // constructor takes the lock
    auto data = parse(file);
    // ...
}   // scope ends: destructors run in reverse order, always.
    // lock released, file closed, even if parse() threw an exception.

This is called RAII, short for Resource Acquisition Is Initialization. The name is confusing, but the idea is short. The constructor takes the resource, and the destructor gives it back. The destructor always runs when the block ends, so the cleanup can't be forgotten. That's also true when the function returns early or when an error is thrown.

Other languages ask you to write the cleanup yourself. Java and Python have finally blocks, and Go has defer. In C++ the type does the cleanup for you.

file is openlock is heldOPEN FILETAKE LOCKPARSERELEASE LOCKCLOSE FILEconstructors, in orderdestructors, in reverse order,however the scope is left
The scope from the code above as a timeline. The lock is taken second, so it is released first.

The standard library uses RAII everywhere. std::string frees its text, std::vector frees its elements, std::ofstream writes out and closes its file, and std::lock_guard releases its lock. Most of modern C++ is about making every resource work this way. The next section does the same for memory.

Smart pointers: new and delete are for library authors

Memory taken with new has to be given back with delete. If you forget, the memory leaks, which means it stays in use until the program ends. If you call delete twice on the same memory, that's . Modern C++ avoids both problems by putting heap memory inside types called smart pointers.

auto p = std::make_unique<Circle>(2.0);   // sole owner, freed when p dies
auto q = std::make_shared<Circle>(3.0);   // reference counted

unique_ptr is the one to use by default. It has exactly one owner, and it's as fast as a plain pointer. It can't be copied, because a copy would mean two owners. It can only be moved, which hands the ownership to someone else.

shared_ptr lets several owners share one object. It keeps a count of its owners and frees the object when the count reaches zero. Keeping that count costs a little time, and real programs need shared ownership less often than it first seems.

unique_ptrone ownerpCIRCLEon the heapfreed when pgoes awayshared_ptrcounted ownersqrCIRCLEcount: 2freed when thecount reaches 0
Ownership as each smart pointer expresses it.

The modern rule is short.

Application code shouldn't need delete. Ownership belongs in types, not in what you remember about the codebase.

Plain pointers are still used, but only with one meaning: "I can use this object, but I don't own it, so I don't free it."

Classes: construction, copying, and moving

class Circle {
public:
    explicit Circle(double r) : radius_(r) {}
    double area() const { return 3.14159265 * radius_ * radius_; }
private:
    double radius_;
};

Here is what each part does.

  • Members of a class are private by default. A struct is the same thing, except that its members are public by default.
  • The const after area() promises that the method doesn't change the object.
  • explicit stops the compiler from turning a double into a Circle on its own. Without it, passing 2.0 where a Circle is expected would quietly create one. This is one of several places in C++ where the risky behaviour is the default and you have to turn it off.

The bigger question is what happens when an object is copied. C++ objects are values, so assigning one object to another copies its contents. For a vector of a million numbers, that's a lot of work.

C++11 added move semantics to avoid that work.

std::vector<double> a = makeBigVector();
auto b = a;             // COPY: allocate and duplicate a million doubles
auto c = std::move(a);  // MOVE: c steals a's internal buffer. Three
                        // pointers change hands and a is left empty.
COPYauto b = a;a3 pointersa million doublesb3 pointersa million morea second buffer is allocatedand every element is copiedMOVEauto c = std::move(a);aemptya million doublesc3 pointersthree pointers change hands,the buffer stays where it is,and a is left empty
A vector is three pointers and a buffer. Copying duplicates the buffer, and moving only hands over the pointers.

A move hands over the data inside an object instead of copying it. Most of the time you don't write std::move yourself. When a function returns a local variable, C++ moves it automatically, or skips the copy completely.

This is why C++ containers are cheap to return from a function and cheap to pass along. They only cost a full copy when you really ask for a second copy. Moving is also how a unique_ptr changes owner, since it can't be copied.

Templates: generics that compile to nothing

A template is code written once for any type. The compiler then writes a separate version of that code for each type you use it with.

template <typename T>
T maxOf(T a, T b) {
    return a > b ? a : b;
}

maxOf(3, 7);        // compiler generates maxOf<int>
maxOf(2.5, 1.5);    // and a separate maxOf<double>

Each generated version is the same code you would have written by hand for that type. Nothing is checked or converted while the program runs, so a template costs nothing at run time. That's the zero-overhead principle again.

maxOf<T>the templateCOMPILERmaxOf(3, 7)maxOf<int>maxOf<double>maxOf(2.5, 1.5)a separate copyfor each type
One template, and one generated function for each type it is used with.

The cost is paid while compiling instead. Builds take longer, and the error messages used to be very long. A typo deep inside a template could produce two hundred lines of errors. C++20 added concepts, which let you state what a type must support. If a type doesn't fit, you get a short error that says why.

template <std::integral T>   // clear requirement, clear error if violated
T half(T x) { return x / 2; }

The STL: containers, iterators, and algorithms

The STL (Standard Template Library) is the part of the standard library that is built from templates. It has three kinds of parts.

  • Containers hold data. std::vector is one.
  • Algorithms work on data. std::sort is one.
  • Iterators connect the two. An iterator points at one element and can step to the next one.

Every algorithm is written against iterators, not against one particular container. So std::sort works on any container that can hand it iterators. With 10 algorithms and 10 containers, the library needs 20 pieces of code instead of 100.

std::vectorstd::stringstd::unordered_mapITERATORSbegin(), end()std::sortviews::filterand the restN containers store thingsM algorithms work on themthe interface between
Each container and each algorithm is written once, against the iterator interface in the middle.
std::vector<int> v = {5, 3, 1, 4, 2};   // the default container
std::sort(v.begin(), v.end());
for (int x : v) std::cout << x << ' ';   // 1 2 3 4 5

std::unordered_map<std::string, int> ages{{"ada", 36}, {"linus", 55}};
ages["grace"] = 85;

Use std::vector unless you have measured a reason to use something else. Its elements sit next to each other in memory, and the loads memory into its 64 at a time, so the next element is usually already there. Because of that, a vector is faster than a linked list at most real sizes, even for operations where a linked list should win on paper.

A few more types you will see often. std::string holds text. std::unordered_map is a hash table, which finds a value by its key. std::optional<T> holds either a value or nothing, and C++ uses it where Go would return a value and an ok flag.

Since C++20, ranges let you chain algorithms without writing begin() and end() each time.

auto evens = v | std::views::filter([](int x) { return x % 2 == 0; });

The [](int x) { ... } part is a lambda, which is a small function without a name, written right where it's used. Modern STL code uses everywhere.

Errors: exceptions, mostly

C++ handles errors the opposite way from Go. A function that fails throws an exception. The exception travels back through the functions that called it until it reaches a catch. Every function it passes through on the way has its objects destroyed, so their destructors run. That's why RAII and exceptions work well together. Nothing is left open.

THE CALL STACK,NEWEST ON TOPparse()throwsloadConfig()owns a file and a lockmain()has the catchthrowits destructors run:lock released, file closedcaught and handled
A throw travelling down the call stack to the nearest catch. Every frame it leaves has its destructors run.
try {
    auto config = loadConfig("config.json");   // may throw
} catch (const std::exception& e) {
    std::cerr << "failed: " << e.what() << '\n';
}

In practice, C++ projects don't all agree on this. Game engines, and codebases that follow Google's style guide, often turn exceptions off because their cost is hard to predict. They return error codes instead, or C++23's std::expected, which holds either a value or an error. When you start reading a C++ codebase, check which of these it uses.

The dialect problem, and the way through

C++ never removes old features. C-style , raw new, char* strings, 1990s class hierarchies, C++11 move semantics and C++20 concepts all still compile today, sometimes in the same file.

So C++ is really a family of styles, and each codebase picks one. Here is what I'd do as a learner.

  • Write modern C++ from day one. Use auto, range-based for loops, smart pointers, STL containers and lambdas. Treat raw new, delete and C-style arrays as outdated.
  • Turn on the compiler's checks. Always use -Wall -Wextra. In debug builds, add -fsanitize=address,undefined. These sanitizers watch the program while it runs and catch the memory mistakes that the language itself doesn't.
  • Read the C++ Core Guidelines. They are the closest thing to an official answer about which style to write, and Stroustrup edits them himself, together with Herb Sutter.
A round portrait of Herb Sutter, with his name below.
Herb Sutter, who edits the C++ Core Guidelines with Bjarne Stroustrup, on a conference panel in 2009. For about twenty years he led the ISO committee that writes the C++ standard.Photo: Microsoft PDC, CC BY 2.0, via Wikimedia Commons (original). Changes: cropped to a circle and placed on a card with the name.

Next Steps

A Tour of C++ by Stroustrup is short, it covers modern C++, and it's the right first book. cppreference.com is the reference you will use every day. Compiler Explorer shows the that your C++ turns into.

A good first project is a command-line tool that reads a file into a vector of and answers questions about the data. It's small enough to finish, and it makes you use ownership, references and the STL properly.

To sum up, C++ gives you full control over the machine. Its modern features cost nothing at run time and clean up after themselves, as long as you follow the modern habits. The language trusts you completely, and those habits mean you rarely need that trust.

Check yourself

3 questions · nothing is saved
  1. 1.How should a function receive a large std::string that it only reads?
  2. 2.When does a std::lock_guard give its lock back?
  3. 3.a is a vector of a million doubles. What does auto c = std::move(a); do?

References & Primary Sources

Official specifications, standards, and documentation cited in this post.

  1. [1]

    The international standard defining modern C++20 language features, memory model, and standard library.

    STANDARDiso.org
  2. [2]

    Authored by Bjarne Stroustrup and Herb Sutter, guiding modern idiomatic C++, RAII, and type safety.

    DOCSisocpp.github.io
  3. [3]

    Authoritative community reference documentation for C++ standard library, templates, and STL algorithms.

    DOCSen.cppreference.com

Who wrote this

Author profile and background

Takumi Yamada

Takumi Yamada

· Backend Engineer

Backend engineer building services, databases, Linux tooling, and NEGEN SYSTEMS. Writing about low-level mechanics, distributed systems, and real-world security.

End of post
NEGEN SYSTEMS
Receipt · post 13 of 31
Written
Feb 5, 2026
Length
2,501 words · 11 min
Built
…
Served by
…
Delivered
…
Over the wire
…
Go's share
…
Next in Programming Languages 101 · part 2 of 6

Go 101: A Small Language for Big Systems

Go has very few features, and that's on purpose. Types, slices, interfaces, errors and goroutines: the core of the language in one post, with the reason behind each design choice.

10 min read
From other series