3 ms·
>std::shared_ptr means I don't have to manage any memory; no more new/delete! (But try as I might to understand std::unique_ptr, I'm just not there yet.) Eh? u
by cgrealy 5y ago
>std::shared_ptr means I don't have to manage any memory; no more new/delete! (But try as I might to understand std::unique_ptr, I'm just not there yet.)
Eh? unique_ptr is just a scoped resource. You create a thing (or take ownership of said thing) and it gets deleted when it goes out of scope. Am I missing something?
It should be the first thing you reach for if you need to dynamically create an object (certainly way before shared_ptr).
- kilotaras 5y agoA simple variable would be a scoped resource, unique_ptr can be transferred. { RAII file = ....; // do stuff } // file is no longer open vs unique_ptr<RAII> outer_ptr; { unique_ptr<RAII> file = make_unique(...); // do stuff outer_ptr = file; } // resource still open
- spacechild1 5y agoYour “RAII“ object can also be transferred if it supports move semantics (it really should). Both classes hold a unique resource (a file handle resp. a heap allocated object) that can be moved but not copied and the resource gets freed when the variable goes out of scope.
- cgrealy 5y agoYeah, I’m aware of that. I still don’t think it adds much to the complexity of unique_pet though. It’s certainly less complicated than its ancestor auto_ptr.