Shared_ptr is similar to STD ::unique_ptr in C++. The main difference between STD :: shareD_Ptr and STD :: Unique_Ptr is that STD :: shareD_Ptr uses reference counting to track the number of references. This means that there can be multiple STD :: shareD_ptr instances pointing to the same dynamically allocated block of memory, which is only released when the last reference object leaves its scope. It is worth noting that STD ::shared_ptr cannot be used to manage C-style dynamic arrays. Here’s an example:

#include <cassert>
#include <iostream>
#include <memory>

class Any {};

int main(void) {
    auto p1 = std::make_shared<Any>();
    assert(p1.use_count() == 1);
    {
        auto p2 = p1;
        std: :shared_ptr<Any> p3;
        p3 = p1;
        assert(p1.use_count() == 3);
        assert(p2.use_count() == 3);
        assert(p3.use_count() == 3);
    }
    assert(p1.use_count() == 1);
    return 0;
}

Copy the code
  • shared_ptrThe smart pointer can only passThe assignmentandThe constructorTo increase the reference count. If the same pointer is assigned separately toshared_ptrCauses a double free error.
  • Sharing ownership of the same objectshared_ptrDestructions on multiple threads do not require external locking protection because reference counting modifications are atomic operations.