c++ share ptr的使用

关于share_ptr cppreferrence的介绍

std::shared_ptr

std::shared_ptr
 
Defined in header <memory>
   
templateclass T class shared_ptr;
  (since C++11)
     

std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer. Several shared_ptr objects may own the same object.

1.The object is destroyed and its memory deallocated when either of the following happens:

  • the last remaining shared_ptr owning the object is destroyed;
  • the last remaining shared_ptr owning the object is assigned another pointer via operator= or reset().

2. The object is destroyed using delete-expression or a custom deleter that is supplied to shared_ptr during construction.

3. A shared_ptr can share ownership of an object while storing a pointer to another object. This feature can be used to point to member

objects while owning the object they belong to. The stored pointer is the one accessed by get(), the dereference and the comparison operators.

The managed pointer is the one passed to the deleter when use count reaches zero.

shared_ptr may also own no objects, in which case it is called empty (an empty shared_ptr may have a non-null stored pointer if the aliasing constructor was used to create it).

All specializations of shared_ptr meet the requirements of CopyConstructibleCopyAssignable, and LessThanComparable and are contextually convertible to bool.

All member functions (including copy constructor and copy assignment)

can be called by multiple threads on different instances of shared_ptr

 without additional synchronization even if these instances are copies and share ownership of the same object.

If multiple threads of execution access the same instance of shared_ptr without synchronization and any

of those accesses uses a non-const member function of shared_ptr then a data race will occur;

the shared_ptr overloads of atomic functions can be used to prevent the data race.

shared_ptr是一个智能指针,它通过指针保留对象的共享所有权。多个shared_ptr对象可以拥有同一个对象。当发生以下任何一种情况时,对象将被销毁并释放其内存:

拥有对象的最后一个剩余的shared_ptr被销毁;

拥有对象的最后一个shared_ptr通过operator=或reset()分配另一个指针。

使用delete-expression或在构造过程中提供给shared_ptr的自定义删除器销毁对象。

shared_ptr可以共享一个对象的所有权,同时存储指向另一个对象的指针。此特性可用于在拥有成员对象所属的对象时指向成员对象。存储的指针是由get()、解引用和比较操作符访问的指针。托管指针是在使用计数为零时传递给删除器的指针。

shared_ptr也可能不拥有对象,在这种情况下它被称为空的(如果使用别名构造函数创建空的shared_ptr,则空的shared_ptr可能有一个非空的存储指针)。

shared_ptr的所有专门化都满足CopyConstructible、CopyAssignable和LessThanComparable的要求,并且可以上下文转换为bool。

所有成员函数(包括复制构造函数和复制赋值)都可以由shared_ptr的不同实例上的多个线程调用,而无需额外的同步,即使这些实例是同一个对象的副本并共享其所有权。如果多个执行线程不同步地访问shared_ptr的同一个实例,并且其中任何一个访问都使用了shared_ptr的非const成员函数,那么就会发生数据竞争;原子函数的shared_ptr重载可用于防止数据竞争。

 

 

posted @ 2022-10-08 20:47  ID是菜鸟  阅读(212)  评论(0编辑  收藏  举报