Which kind of pointer do I use when?

后端 未结 4 1085
遥遥无期
遥遥无期 2020-11-22 03:39

Ok, so the last time I wrote C++ for a living, std::auto_ptr was all the std lib had available, and boost::shared_ptr was all the rage. I never rea

4条回答
  •  生来不讨喜
    2020-11-22 04:12

    Cases of when to use unique_ptr:

    • Factory methods
    • Members that are pointers (pimpl included)
    • Storing pointers in stl containters (to avoid moves)
    • Use of large local dynamic objects

    Cases of when to use shared_ptr:

    • Sharing objects across threads
    • Sharing objects in general

    Cases of when to use weak_ptr:

    • Large map that acts as a general reference (ex. a map of all open sockets)

    Feel free to edit and add more

提交回复
热议问题