简体   繁体   中英

Shared pointer lifetime

If I dereference a shared_ptr and invoke a method on the contained object, is the shared_ptr lifetime guaranteed?

Let's say:

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

Where linkInfoPtr is shared_ptr and stored in the stream object. Does it mean if linkInfoPtr would be destroyed from another thread during addTxRxBytes invocation I would face a segfault?

If another thread destroys linkInfoPtr 's in a manner that is not synchronized with the line

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. 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.


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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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