4 ms·
std::make_shared exists to allocate the control block at the same time as the memory itself. This has a pretty major disadvantage, the memory for the shared poi
by maccard 3y ago
std::make_shared exists to allocate the control block at the same time as the memory itself. This has a pretty major disadvantage, the memory for the shared pointer won't be deallocated until the last std::weak_ptr has been destroyed, even if the object has been destroyed.
- pjmlp 3y agoAnd the major advantage that object data by being coupled with control block reduces fragmentation, and avoids the error of wrongly handling memory leaks when new obj() fails as parameter to shared pointer construction.
- maccard 3y agoYep, I realise I only talked about the negatives, not the advantages. In general I prefer to use make_shared and be careful with uses of weak pointers.
- elteto 3y agoAh good point. But in exchange you get cache locality of control block + data and single instruction deref.
- maccard 3y agoIndeed. It's a tradeoff, and I personally prefer std::make_shared.