std::allocator (C++)
Watch the CppCon talk that Kajanan recommended to me.
Saw this at NVIDIA. Seems that it is really important. I don’t get why we need our own allocators though when you can just call cudaMalloc, or even just use a unique_ptr.
Resources
🧩 1. Containers don’t know how memory was allocated
Each container uses its allocator object to request and free memory.
When you call something like:
std::vector<int, MyAlloc<int>> v(a);
the container will later call:
a.deallocate(ptr, n);
to release the memory.
If another vector w uses a different allocator instance (b), then:
std::vector<int, MyAlloc<int>> w(b);
and you tried to “steal” v’s pointer into w, then eventually w’s destructor would call:
b.deallocate(ptr, n);
But that’s undefined behavior, because b didn’t allocate that memory — a did.
👉 That’s the entire problem.