4 ms·
Raw C or C++ pointers you can’t, at least not trivially. You either have a double pointer masquerading as a single pointer, or some other fanciness. Come to th
by elteto 3y ago
Raw C or C++ pointers you can’t, at least not trivially. You either have a double pointer masquerading as a single pointer, or some other fanciness.
Come to think of it, std::shared_ptr has a control block that points to the actual data. I think implementations allocate the control block and the data contiguously for performance reasons, but you don’t really have to.
- ksherlock 3y agoThere is a std::make_shared( constructor arguments... ) function which will do one allocation for the control block + item data. I don't think compilers will do it automatically (it has other implications over a normal std::shared_ptr) so you need to opt into it.
- maccard 3y agostd::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.
- Conscat 3y ago`boost::intrusive_ptr` or the proposed `std::retained_ptr` is required to guarantee that.