How do shared pointers work?

前端 未结 5 1858
无人共我
无人共我 2020-12-02 13:34

How do shared pointers know how many pointers point to that object? (shared_ptr, in this case)

5条回答
  •  甜味超标
    2020-12-02 13:51

    "Shared pointer is a smart pointer (a C++ object wih overloaded operator*() and operator->()) that keeps a pointer to an object and a pointer to a shared reference count. Every time a copy of the smart pointer is made using the copy constructor, the reference count is incremented. When a shared pointer is destroyed, the reference count for its object is decremented. Shared pointers constructed from raw pointers initially have a reference count of 1. When the reference count reaches 0, the pointed object is destroyed, and the memory it occupies is freed. You do not need to explicitly destroy objects: it will be done automatically when the last pointer's destructor runs. " From here.

提交回复
热议问题