// ======================================================================== // /content/posts/languages/cpp-notes.typ // ======================================================================== #import "@tola/source:0.0.0": tola-meta #import "@tola-modules/nasapunk:0.0.0": callout, cols, xref #import "/figures/cpp-notes.typ" as fig #tola-meta(( title: "C++ Notes", date: "2026-03-18", summary: "C++ details I ran into while writing an inference engine on ggml: when members are constructed, references, pointers to pointers, and what goes in a header.", tags: ("Dev", "C++"), weight: 10, )) Things that tripped me up while writing a small inference engine on ggml (see #xref("/posts/ml-systems/ggml-with-cpp/")). The ggml examples are C-style C++, so most of these come from reading them. = Initialization ```cpp struct Member { Member() { std::cout << "Member()\n"; } Member(int x) { std::cout << "Member(" << x << ")\n"; } }; class MyClass { Member m1; Member m2; int value; public: MyClass() { // no initializer list std::cout << "body\n"; value = 10; // assignment, not initialization } MyClass(int v) : m1(1), m2(2), value(v) { // initializer list std::cout << "body\n"; } }; ``` #cols(labels: ([`MyClass a;`], [`MyClass b(42);`]))[ ```text Member() Member() body ``` ][ ```text Member(1) Member(2) body ``` ] *Every member is constructed before the body runs.* Without an initializer list, `m1` and `m2` are default-constructed first, and anything the body does to them is a second step. To construct a member with arguments, or a member that has no default constructor, or a `const` or reference member, use the initializer list. What "default-constructed" means depends on the type: - A class type, such as `std::vector`, runs its default constructor: an empty container. - A raw pointer or an `int` is *not* zeroed. It holds an indeterminate value until something assigns it, unless it has a default member initializer such as `ggml_context * ctx = nullptr;`. `class` and `struct` differ only in the default access: members and base classes are `private` in a `class` and `public` in a `struct`. = Reference A reference is another name for an existing variable. It binds to the variable, not to the value the variable holds at that moment. `examples/gpt-2/main-ctx.cpp` in ggml uses this when loading the model. `model.ctx_w` is a `ggml_context *` member, and it has no value yet when the reference is taken: ```cpp auto & ctx = model.ctx_w; // ctx is another name for model.ctx_w { struct ggml_init_params params = { /*.mem_size =*/ ctx_size, /*.mem_buffer =*/ NULL, /*.no_alloc =*/ false, }; model.ctx_w = ggml_init(params); } // later: ctx sees the pointer assigned above model.ln_f_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); ``` With `auto ctx = model.ctx_w;` (no `&`), `ctx` would be a copy of the indeterminate pointer, and the later calls would pass garbage to ggml. = Pointer To let a function set a pointer that the caller owns, the caller passes the pointer's address. `gguf_init_from_file` returns its tensor metadata this way: ```cpp struct ggml_context * ctx = NULL; // a pointer whose value is NULL struct gguf_init_params params = { /*.no_alloc = */ true, /*.ctx = */ &ctx, // the address of ctx, not its value }; struct gguf_context * gguf = gguf_init_from_file(fname, params); // ctx now points to a ggml_context ``` `&ctx` has type `ggml_context **`. Its value is where `ctx` lives on the stack, which is never NULL, even though `ctx` itself is. Inside, `gguf.cpp` writes through it: `*params.ctx = ggml_init(pdata);`. #figure(fig.fig-pointer(), caption: [`ctx` and `&ctx`: `gguf_init_from_file` writes through `params.ctx` into the variable `ctx`.]) = Header Files A header (`.h`) holds what other files need in order to _use_ something: - class and struct declarations; - function declarations; - full definitions of `inline` functions and templates, since the compiler needs the body at every call site; - constants and type aliases (`typedef`, `using`). A source file (`.cpp`) holds the rest: function bodies, member function bodies, and definitions of static variables. *Including a header does not bring in its `.cpp`.* `#include` pastes the declarations; the linker finds the definitions in the object file compiled from the `.cpp`: ```cpp // main.cpp #include "person.h" // declarations only int main() { Person p("Alice", 25); // the linker finds the body in person.o p.introduce(); } ``` So in CMake, only `.cpp` files go into `add_executable` or `add_library`: #table( columns: 2, table.header([Files], [Add to `CMakeLists.txt`?]), [Header only (`.h`)], [No], [Header + source (`.h` + `.cpp`)], [The `.cpp` only], [Source only (`.cpp`)], [Yes], ) // ======================================================================== // /figures/cpp-notes.typ // ======================================================================== // Figures for content/posts/languages/cpp-notes.typ, drawn with cetz. // Same conventions as /utils/figure.typ: 1pt per unit, y grows upward, < ~560pt wide. #import "@tola-modules/nasapunk:0.0.0": cetz #import "@tola-modules/nasapunk:0.0.0": arrow, c #let txt(body, size: 9pt, fill: c.muted, weight: 400) = text(size: size, fill: fill, weight: weight, body) #let head(body, fill: c.ink) = text(size: 9pt, weight: 700, fill: fill, body) /// `&ctx` is the address of the variable `ctx`, not its (NULL) value. #let fig-pointer() = cetz.canvas(length: 1pt, { import cetz.draw: * let (w, ch) = (120, 24) let cell(x, name, ty, value, addr, addr-fill: c.muted) = { rect((x, 0), (x + w, -ch), fill: white, stroke: .8pt + c.line) content((x + w / 2, -ch / 2), value) content((x, 5), txt(name, fill: c.ink, weight: 700) + h(6pt) + txt(ty, size: 8pt), anchor: "south-west") content((x, -ch - 5), txt(addr, size: 8pt, fill: addr-fill), anchor: "north-west") } rect((-12, 46), (346, -50), fill: c.panel, stroke: none, radius: 4pt) content((-4, 42), head("STACK", fill: c.muted), anchor: "north-west") rect((362, 46), (512, -50), fill: c.panel, stroke: none, radius: 4pt) content((370, 42), head("HEAP", fill: c.muted), anchor: "north-west") cell(0, "params.ctx", "ggml_context **", txt("0x7fff1234", fill: c.blue, weight: 600), "at 0x7fff1200") cell(210, "ctx", "ggml_context *", txt(strike[NULL]) + h(8pt) + txt("0x6000a0c0", fill: c.orange, weight: 600), "at 0x7fff1234", addr-fill: c.blue) cetz.draw.content((437, -12), name: "obj", box( fill: c.orange1, stroke: (paint: c.orange, thickness: .8pt, dash: "dashed"), radius: 4pt, inset: (x: 7pt, y: 5pt), text(size: 9pt, weight: 600, fill: c.ink, "ggml_context"), )) arrow((w + 4, -12), (206, -12), color: c.blue, w: .9pt) content(((w + 210) / 2, -8), txt("value = &ctx", size: 8pt, fill: c.blue), anchor: "south") arrow((334, -12), "obj.west", color: c.orange, w: .9pt, dash: "dashed") content((368, -8), txt("after init", size: 8pt, fill: c.orange), anchor: "south") content((-12, -64), txt([① `gguf_init_from_file` receives `&ctx`: not NULL, but the address of the variable `ctx` on the stack.], fill: c.ink), anchor: "north-west") content((-12, -80), txt([② Inside, `*params.ctx = ggml_init(...)` overwrites `ctx` itself.], fill: c.ink), anchor: "north-west") })