How does a reference-counting smart pointer’s reference counting work?

I’ve seen two different non-intrusive approaches to this: The smart pointer allocates a small block of memory to contain the reference counter. Each copy of the smart pointer then receives a pointer to the actual object and a pointer to the reference count. In addition to an object pointer, each smart pointer contains a previous … Read more

How to avoid memory leak with shared_ptr?

If you have circular references like this, one object should hold a weak_ptr to the other, not a shared_ptr. From the shared_ptr introduction: Because the implementation uses reference counting, cycles of shared_ptr instances will not be reclaimed. For example, if main() holds a shared_ptr to A, which directly or indirectly holds a shared_ptr back to … Read more

What is going on: C++ std::move on std::shared_ptr increases use_count?

What is going on, here? On MacOS, it seems that you must explicitly enable move-sematics with -std=c++11 (or later standards)ยน. Otherwise, the example happens to compile (i.e., std::shared_ptr from the related library implementation is usable) but doesn’t work correctly as the required language features aren’t enabled. This results in actual copies being made instead of … Read more

Set shared_ptr with new_pointer that is old_pointer + offset

Yes this is possible. You can use constructor 8, the aliasing constructor from this reference: https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr // make sure you use an array deleter std::shared_ptr<char> osp(new char[1024], std::default_delete<char[]>()); // load the data into your buffer at osp.get() // Find the offset in the data by parsing auto const offset = parse_buffer_for_offset(osp.get()); // Now set a … Read more