简体   繁体   English

共享指针生命周期

[英]Shared pointer lifetime

If I dereference a shared_ptr and invoke a method on the contained object, is the shared_ptr lifetime guaranteed?如果我取消引用shared_ptr并调用包含对象的方法,是否保证 shared_ptr 生命周期?

Let's say:让我们说:

stream.linkInfoPtr->addTxRxBytes( txBytes, rxBytes );

Where linkInfoPtr is shared_ptr and stored in the stream object.其中linkInfoPtrshared_ptr并存储在流对象中。 Does it mean if linkInfoPtr would be destroyed from another thread during addTxRxBytes invocation I would face a segfault?这是否意味着,如果linkInfoPtr会从另一个线程中被破坏addTxRxBytes调用我将面临一个段错误?

If another thread destroys linkInfoPtr 's in a manner that is not synchronized with the line如果另一个线程以与行不同步的方式破坏了linkInfoPtr

stream.linkInfoPtr->addTxRxBytes( txBytes, rxBytes );

in this thread, then your program has a data race and therefore undefined behavior.在此线程中,您的程序会出现数据竞争,因此存在未定义的行为。

Only atomic variables may be accessed potentially in parallel for read and write without any additional synchronization, such as through a mutex or atomic operations.只有原子变量可以潜在地并行访问以进行读写,而无需任何额外的同步,例如通过互斥锁或原子操作。

It does not matter at all that linkInfoPtr is a std::shared_ptr or for what purpose it is written to and read from. linkInfoPtrstd::shared_ptr或者它被写入和读取的目的完全无关紧要。 This is true for all non-atomic types.这适用于所有非原子类型。

And even for an atomic type you would have undefined behavior, because one possible order of accesses would be that linkInfoPtr is destroyed before the other line is executed, in which case you have undefined behavior due to access out-of-lifetime.即使对于原子类型,您也会有未定义的行为,因为一种可能的访问顺序是在执行另一行之前销毁linkInfoPtr ,在这种情况下,由于访问生命周期外,您有未定义的行为。


Each thread needs its own copy of the std::shared_ptr and then you are guaranteed that the object the std::shared_ptr share ownership over and that you are calling addTxRxBytes on is alive until the calling thread destroys its instance of the std::shared_ptr .每个线程都需要自己的std::shared_ptr副本,然后您可以保证std::shared_ptr共享所有权的对象以及您正在调用addTxRxBytes的对象是活着的,直到调用线程销毁其std::shared_ptr实例.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM