Original Questions:
Answers:
Yes, the first two questions are accurate. std::shared_ptr's reference counting and destructor invocation are thread-safe.
The third question is also correct. std::shared_ptr does not guarantee thread safety for the object stored within it. The object itself may not be thread-safe, and therefore, accessing it from multiple threads without proper synchronization could lead to undefined behavior.
Example:
Consider the following piece of pseudocode:
// Thread I shared_ptr<A> a (new A (1)); // Thread II shared_ptr<A> b (a); // Thread III shared_ptr<A> c (a); // Thread IV shared_ptr<A> d (a); d.reset (new A (10));
This is because reset() doesn't affect other threads' references to the same object. d is the only shared pointer that will point to the new instance, while the other references (a, b, and c) will remain pointing to the original instance.
The above is the detailed content of Is std::shared_ptr thread-safe for the object it manages?. For more information, please follow other related articles on the PHP Chinese website!