c++ - std::unique_ptr vs std::shared_ptr vs std::weak_ptr vs std::auto_ptr vs raw pointers -


what equivalent uses of each smart pointer in comparison similar (but not limited to) advanced techniques using raw pointers?

my understanding minimal, can gather:

  • raw pointers: use if really, really, really, really, know doing , have hidden usage behind interface.
  • std::auto_ptr: obsolete never use.
  • std::unique_ptr: singleton pointer transfers ownership upon assignment.
  • std::shared_ptr: reference counted pointer not transfer ownership upon assignment increments reference count. when references leave scope or explicitly std::shared_ptr::reset underlying deallocator called.
  • std::weak_ptr: sub-type std::shared_ptr not increment reference count , invalidated when parent std::shared_ptr no longer exists. may return , invalid reference. check before using.

raw pointer equivalent examples

reference counting, cache implementations: std::map<std::string, std::pair<long, bitmap*> > _cache;

singletons transfer of ownership:

class keyboard { public: //...     static keyboard* createkeyboard();     ~keyboard(); //... private: //...     keyboard();     static keyboard* _instance; //... }; 

aggregate containers, no ownership: spatial partitioning graphs , trees, iterative containers, etc.

composite containers, ownership: large objects.

--edit--

as working came upon interesting case, deadmg pointed out smart pointers supposed used easy abstractions take care of resource management; file-scope objects can not created on heap @ point of declaration instead must created @ later time?

what idiom each smart pointer supposed replace?

every single 1 of them, ever, involved destroying pointed-to resource. in other words, virtually of them. can think of no idioms involving raw pointers did not involve destroying pointed-to resource. every other use isn't idiom, it's "using pointer".


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -