Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
Guide

Understanding std::unique_ptr custom deleters: function pointers vs lambda stateless deleters [StackOverflow Architecture Guide]

raii_clean_coder
Modern C++ Advocate
MEMBER
Өкіл: 190
Қосылу күні: Aug 2020
Хабарламалар: 20
Рахмет: 22
1 ай бұрын · Jul 5, 2026 7:24 PM
#1

Why specifying a custom deleter in std::unique_ptr changes its memory size:

  1. Stateless Struct Deleter:
CPP
   struct FreeDeleter { void operator()(void* p) const { std::free(p); } };
   std::unique_ptr<int, FreeDeleter> p(ptr);
   // sizeof(p) == 8 bytes (Empty Base Optimization / [[no_unique_address]])!
  1. Function Pointer Deleter:
CPP
   std::unique_ptr<FILE, decltype(&fclose)> f(fp, &fclose);
   // sizeof(f) == 16 bytes! (Stores an extra 8-byte function pointer inside the smart pointer object!)
modern_cpp_artisan
C++ Template Wizard
MEMBER
Өкіл: 124
Қосылу күні: Jun 2019
Хабарламалар: 29
Рахмет: 72
1 ай бұрын · Jul 5, 2026 10:40 PM
#2

Always prefer a stateless functor or empty struct deleter over raw function pointers to keep std::unique_ptr exactly 8 bytes.

memory_model_mook
Low-Level C Veteran
MEMBER
Өкіл: 163
Қосылу күні: Jan 2019
Хабарламалар: 11
Рахмет: 33
1 ай бұрын · Jul 6, 2026 1:34 PM
#3

Great tip. Keeping unique_ptr at 8 bytes means it passes in a single CPU register (rdi/rcx) under standard calling conventions.