I wrote in "Linux multithreaded Server programming: Using the Muduo C + + network Library" section 1.9, "re-discuss shared_ptr thread safety" in the article:
(shared_ptr) The reference count itself is secure and unlocked, but the object's read-write is not because the shared_ptr has two data members and the read-write operation cannot be atomized. According to the document (http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm#ThreadSafety), the thread security level and the built-in type of the shared_ptr, Standard Reservoir, std::string, namely:
A shared_ptr object entity can be read concurrently by multiple threads (document example 1);
Two shared_ptr object entities can be written by two threads at the same time (example 2), and "destructor" to write operations;
If you want to read and write the same shared_ptr object from multiple threads, you need to lock (example 3~5).
Note that the above is the thread-safe level of the shared_ptr object itself, not the thread-safe level of the object it manages.
The latter text (p.18) describes how to lock and unlock efficiently. This article specifically analyzes why "because shared_ptr has two data members, read and write operation can not be atomized" so that multithreading read and write the same shared_ptr object need to lock. It seems to me that the obvious conclusions are also questionable, which will lead to disastrous consequences and deserve my writing this article. Taking Boost::shared_ptr as an example, this paper may be slightly different from std::shared_ptr.
Data structure of shared_ptr
SHARED_PTR is a reference-counting (reference-counting) smart pointer, where almost all implementations use a count (counting) on the heap (heap) (in addition to the theoretical use of circular lists, but no instances). Specifically,,shared_ptr<foo> contains two members, one pointing to Foo's pointer ptr and the other Ref_count pointer (its type is not necessarily the original pointer, possibly the class type, but does not affect the discussion here), pointing to the Ref_co on the heap Unt object. The Ref_count object has multiple members, and the concrete data structure is shown in Figure 1, where deleter and allocator are optional.
Figure 1:shared_ptr the data structure.
To simplify and highlight the focus, the following text only draws the Use_count value:
The above is shared_ptr<foo> x (new Foo); The corresponding memory data structure.