cpp / expert
Snippet
Intrusive Resource Management for Performance-Critical Systems
Intrusive pointers store the reference count inside the object itself rather than in a separate control block (as std::shared_ptr does). This improves cache locality and reduces the number of dynamic allocations, which is critical in game engines and kernels.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
struct IntrusiveBase {mutable int ref_count = 0;void retain() const { ++ref_count; }void release() const {if (--ref_count == 0) delete this;}protected:virtual ~IntrusiveBase() = default;};class DataNode : public IntrusiveBase {// Node payload};
Breakdown
1
mutable int ref_count = 0;
Stores the counter within the object; 'mutable' allows incrementing even if the object is accessed via a const pointer.
2
if (--ref_count == 0) delete this;
The object takes responsibility for its own destruction once all references are dropped.