top | item 27597345

(no title)

haldean | 4 years ago

There's a crazy downside to make_shared that I learned recently because of this: if you have a weak pointer to a shared thing, and the refcount for the shared thing drops to zero, the weak pointers will keep the allocation for the object "alive", because they still need access to the remnant and the remnant was created in the same allocation as the object so they can't be freed separately. So now I only use make_shared if I know for sure there won't be a weak_ptr pointing at it (or if the base object has a relatively small memory footprint after it's been destructed).

discuss

order

Asooka|4 years ago

Won't the object be destructed though? So while the memory for the object is kept, the memory for the object's heap-allocated members is not. I.e. if you have a 100mb string, after only weak references are left you won't have 100mb memory taken, but only sizeof(string) + sizeof(control block).

nneonneo|4 years ago

Depends on the object. As OP notes, `make_shared` with weak pointers is fine "if the base object has a relatively small memory footprint after it's been destructed".

There's lots of cases where the object itself is big, though. Think of objects with big fixed arrays, "god objects" with a bajillion pointers, or objects which themselves allocate data in-line.

ot|4 years ago

Yeah, that's definitely something to be aware of. It's usually not an issue as most objects have small footprint (and any allocations they in turn hold would be released when the strong refcount goes to 0).