skip to content

Why does a C++ CRTP instance-counting mixin keep a separate count per derived class, and how can its count go negative?

level: middleimportance: should knowfreq 35%

answer

  1. one specialization per argument
  2. static member per specialization
  3. copies bypass the default constructor
  4. the implicit copy constructor counts nothing

basics

~20 s

Each InstanceCounter<Derived> is a distinct class, so its static member is a separate variable for every derived type. The count goes negative when the mixin declares only a default constructor: copies use the implicit copy constructor, which never increments, yet their destructors decrement.

solid answer

~40 s

A mixin is a base that adds members to whatever class inherits it. With CRTP, `struct Mesh : InstanceCounter<Mesh>` and `struct Texture : InstanceCounter<Texture>` derive from two different classes, so a `static inline int alive` inside the template is two different variables: each type counts only its own objects. A non-template base would give every type one shared count. The classic bug is forgetting copies: if the mixin declares only a default constructor and a destructor, copying a `Mesh` uses the implicitly declared copy constructor of `InstanceCounter<Mesh>`, which does not touch `alive`, while every destructor still decrements it. Declaring `InstanceCounter(const InstanceCounter&)` that also increments fixes it; moves then fall back to that copy constructor, since a user-declared copy constructor suppresses the implicit move constructor.

code

cpp · 19 lines
cpp
#include <iostream>

template <class Derived>
struct InstanceCounter {
    static inline int alive = 0;  // one variable per InstanceCounter<Derived>
    InstanceCounter() { ++alive; }
    InstanceCounter(const InstanceCounter&) { ++alive; }
    ~InstanceCounter() { --alive; }
};

struct Mesh : InstanceCounter<Mesh> {};
struct Texture : InstanceCounter<Texture> {};

int main() {
    Mesh m1, m2;
    Mesh m3 = m1;
    { Texture t; std::cout << Texture::alive << '\n'; }  // 1
    std::cout << Mesh::alive << ' ' << Texture::alive << '\n';  // 3 0
}

go deeper

for a junior

Recall that a class template's specializations are separate classes, each with its own static members.

for a middle

Walk through why a copied object is never counted when only a default constructor exists, and show the counting copy constructor that fixes it.

for a senior

Harden the mixin: a protected destructor against deletion through the base, std::atomic when threads create objects, and a check that moves still count correctly.

for a principal

Judge when a per-type mixin beats instrumenting each class by hand: it removes repetition, but every class now carries a template base that shows up in its type and its error messages.

## What a mixin is in C++ A **mixin** is a small base class whose only job is to add members, such as functions, data or behaviour in the constructor and destructor, to any class that inherits from it. In C++ the natural way to write one that adapts to each user is CRTP: the mixin is a class template `InstanceCounter<Derived>`, and each class inherits it with its own name as the argument. A rendering engine wants to know how many meshes and how many textures are alive, to spot leaks between levels: - `struct Mesh : InstanceCounter<Mesh> { ... };` - `struct Texture : InstanceCounter<Texture> { ... };` - `Mesh::alive` and `Texture::alive` then report each type's own count. ## Why every derived type gets its own counter A class template is not a class; each **specialization** is. `InstanceCounter<Mesh>` and `InstanceCounter<Texture>` are two unrelated classes generated from one template, and a static data member belongs to the class, so each specialization has its own `alive`. Declaring it `static inline int alive = 0;` (an inline variable, C++17) lets the definition live in the header with no separate out-of-class definition. Compare the alternatives: | Design | Counters | Notes | |---|---|---| | `struct Counted` (no template) | one shared count for all types | every class adds to the same number | | `InstanceCounter<Derived>` (CRTP) | one count per derived type | the argument makes each base distinct | | a counter member in each class | one per type | the same code repeated in every class | The CRTP argument is not even used inside the mixin's functions here. Its only role is to make the base class different for each user. ## The negative count: copies bypass the constructor you wrote The naive version declares a default constructor that increments and a destructor that decrements. Copying a `Mesh` then goes wrong: 1. `Mesh b = a;` calls `Mesh`'s implicit copy constructor. 2. That copies the base subobject with `InstanceCounter<Mesh>`'s **implicitly declared copy constructor**, which copies nothing and increments nothing. 3. When `a` and `b` are destroyed, the destructor runs twice and decrements twice. Two objects were counted once and uncounted twice, so after both die `alive` is `-1`. A run with Apple clang 21 prints exactly that. The fix is to declare the copy constructor yourself and increment there too: ```cpp InstanceCounter(const InstanceCounter&) { ++alive; } ``` Two consequences follow from the special-member rules: - Declaring a copy constructor **suppresses the implicit move constructor**, so a move of `Mesh` also uses this copy constructor for the base, which is what you want: a moved-from object is still alive and will still be destroyed. - **Copy assignment** needs nothing: assigning one live object to another changes no count, and the implicitly declared copy assignment operator still exists. ## Making the mixin hard to misuse - Give the mixin a **protected destructor**, so nobody deletes a `Mesh` through an `InstanceCounter<Mesh>*`. It has no virtual destructor, and a protected one turns that misuse into a compile error. - The mixin adds no data members, so as an empty base it normally takes no space in `Mesh`; the major compilers apply the empty base optimization. - A plain `int` is not safe if objects are created on several threads; use `std::atomic<int>` then. - Several mixins compose naturally: `struct Mesh : InstanceCounter<Mesh>, Printable<Mesh>`. ## Reading the counter The static member is inherited, so both `Mesh::alive` and `InstanceCounter<Mesh>::alive` name the same variable. That makes leak checks cheap to write: - after unloading a level, a debug build can `assert(Mesh::alive == 0 && Texture::alive == 0);` - a test can create and copy objects, then check the count went back to its starting value; - a debug overlay can list the live count of every counted type next to its name. Because the count lives in the mixin, adding the check to a new class is one entry in its base list, and removing it is the same edit in reverse. ## Why interviewers ask it The question checks two things at once: that you understand a template's specializations are separate classes with separate statics, which is what makes CRTP mixins work, and that you know a copy does not run the default constructor. Candidates who know the pattern but not the special-member rules write the buggy version.

  • Would the mixin still count separately if it were a non-template base with a static member?
    No. A non-template `struct Counted` is one class, so its static `alive` is one variable shared by every class that inherits it: meshes and textures would add to the same number. The CRTP argument is what makes `InstanceCounter<Mesh>` and `InstanceCounter<Texture>` two distinct classes with two distinct statics, even though the mixin's code never uses the argument.
  • Does a move of a Mesh keep the CRTP count correct once the mixin declares a copy constructor?
    Yes. A user-declared copy constructor suppresses the implicitly declared move constructor of `InstanceCounter<Mesh>`, so moving a `Mesh` copies the base with the counting copy constructor. That is correct: the moved-from `Mesh` is still a live object that will be destroyed and decremented later.

  • All classes using the CRTP counter share one static count.
  • Copy construction runs the mixin's default constructor, so copies are counted.
  • The static counter needs a definition in exactly one .cpp file even when declared inline.
  • Copy assignment must increment the count as well.
  • The mixin needs a virtual destructor for the count to work.