Skip to content

Latest commit

 

History

History
107 lines (71 loc) · 4.75 KB

smart_pointers_implementation_details.md

File metadata and controls

107 lines (71 loc) · 4.75 KB

Implementation details


Implementation details – std::unique_ptr<>

  • Just a holding wrapper
  • Holds an object pointer
  • Constructor copies a pointer
  • Call proper delete in destructor
  • No copying
  • Moving means:
    • Copying original pointer to a new object
    • Setting source pointer to nullptr
  • All methods are inline

Implementation details – std::shared_ptr<>

sharedptr2

  • Holds an object pointer
  • Holds 2 reference counters:
    • shared pointers count
    • weak pointers count
  • Destructor:
    • decrements shared-refs
    • deletes user data when shared-refs == 0
    • deletes reference counters when shared-refs == 0 and weak-refs == 0
  • Extra space for a deleter
  • All methods are inline

Implementation details – std::shared_ptr<>

  • Copying means:
    • Copying pointers to the target
    • Incrementing shared-refs

sharedptr3

  • Moving means:
    • Copying pointers to the target
    • Setting source pointers to nullptr

sharedptr4


Implementation details – std::weak_ptr<>

  • Holds an object pointer
  • Holds 2 reference counters:
    • shared pointers count
    • weak pointers count
  • Destructor:
    • decrements weak-refs
    • deletes reference counters when shared-refs == 0 and weak-refs == 0

sharedptr5


Implementation details – std::weak_ptr<>

  • Copying means:
    • Copying pointers to the target
    • Incrementing weak-refs

sharedptr6

  • Moving means:
    • Copying pointers to the target
    • Setting source pointers to nullptr

sharedptr7


std::weak_ptr<> + std::shared_ptr<>

  • Having a shared pointer and a weak pointer

sharedptr8

  • After removing the shared pointer

sharedptr9


Making a std::shared_ptr<>

  • std::shared_ptr<Data> p{new Data};

sharedptr10

  • auto p = std::make_shared<Data>();
    • Less memory (most likely)
    • Only one allocation
    • Cache-friendly

sharedptr11