I'm trying to make sure I correctly understand the semantics of std::shared_ptr
, where:
- Modifications to the underlying shared reference counter (
std::_Sp_counted_base
in the stdc++ implementation that ships with GCC) are thread-safe. - Access to a given instance of an
std::shared_ptr
is not thread-safe.
With that in mind, consider the following snippet:
struct Data {
std::shared_pointer<X> x;
std::shared_pointer<Y> y;
};
void SomeThread1 (Data d) {
std::shared_pointer<X> localxptr = d.x;
...
}
void SomeThread2 (std::shared_ptr<Data> d) {
std::shared_pointer<X> localxptr = d.x;
...
}
Assuming SomeThread[12]
are their own threads, and whoever created them passed the appropriate parameters, am I correct in believing that:
SomeThread1
is safe: Sinced
is a copiedData
,d.x
is therefore a unique instance of theshared_ptr<X>
member and can thus be copied again safely intolocalxptr
.SomeThread2
is not safe: Sinced
is a pointer to aData
,d.x
is therefore the sameshared_ptr<X>
instance that the calling thread has and thus cannot be copied safely intolocalxptr
, which risks both the new thread and the calling thread (and anybody else) accessing that sameshared_ptr<X>
instance.
Is my assessment correct?
Seems obvious, but I just want a sanity check because I've been staring at a lot of code for too long lately.