3 ms·
> effectively have to decide when to free No. You just pass around the unique_ptr. Don't actually pass a reference to the object. When a function is done using
by dragontamer 11y ago
> effectively have to decide when to free
No. You just pass around the unique_ptr. Don't actually pass a reference to the object. When a function is done using the unique_ptr, it gets returned to its parent object.
You'll never have a use-after-free if you use unique_ptr correctly. As others have noted: make_unique() and pass it around with movement semantics.
The worst that can happen is that you dereference NULL (use a unique_ptr after it has been sink'd to another function).
- pcwalton 11y ago> You'll never have a use-after-free if you use unique_ptr correctly. As others have noted: make_unique() and pass it around with movement semantics. This is far too limiting to handle anywhere near every real world use case. For example, you can't really call any non-&& methods on the referent following the discipline you propose, because "this" is a raw pointer!
- dragontamer 11y agoYeah, so use shared_ptr and weak_ptr in those cases. Shared_ptr is basically equivalent to C# and Python garbage collection (loops never get collected). So that should be "good enough" for the generic case. unique_ptr is supposed to be used in a very limited fashion as I described. Its more efficient than shared_ptr, but much much more limited.
- pcwalton 11y agoJust to be clear, you're suggesting to use shared_ptr for every object you want to call methods that don't take "this" by move on? (Which is not enough by any means to ensure memory safety, of course…)
- dragontamer 11y agoObviously, full memory safety is not ensured if you ever move over to raw pointers. But if you're copying shared_ptrs around, the reference counting almost always ensures that the memory is valid. The idea is to rarely use references or raw-pointers unless you know you have to.
- pcwalton 11y agoI'm not questioning how shared_ptr works. I'm claiming that using it as extensively as you describe is totally impractical, and no C++ code works this way.
- dragontamer 11y agoI've found the UWP Windows 10 API to be using shared_ptrs and stuff more often. A lot of things are done 'correctly'. Its mostly when interacting with legacy code (ie: MFC) where issues come up.
- pcwalton 11y agoC++ programs written using UWP make heavy use of references, like all C++ programs, and are highly vulnerable to use after free.