std::auto_ptr has no guarantee of thread safety when invoking a non-constant element, such as reset() , as you suggest. Also, std::unique_ptr , which you should consider as a replacement for auto_ptr , since auto_ptr effectively deprecated.
std::shared_ptr provides such thread safety guarantees.
What you are usually guaranteed with shared_ptr is that the reference count is processed atomically, which means that you are not safe from data races when creating a copy of shared_ptr , provided that no one is currently modifying shared_ptr to this moment.
Consider the following use case for your shared_ptr . You have a global shared_ptr<string> sharedString; , which currently points to an instance of std::string . For many threads, it is safe to call get() to get a pointer to a string. They can also create their own shared pointer to it as follows: shared_ptr<string> myString = sharedString; , provided that no one changes what the general pointer points to.
Now go back and correct the race condition that exists in the example. When it comes time to change what the global common pointer indicates, the thread can make a copy of it - this is a problem because it can leave a copy in an inconsistent state. So, we need to make sure that we change and copy it atomically.
Fortunately for us, shared_ptr provides a number of specializations for C ++ 11 atomic operations: atomic_load , atomic_store and atomic_exchange .
When creating a copy of shared_ptr use atomic_load , and when updating shared_ptr use atomic_store .
The implementation of this method is important for two reasons.
- Atomic_ * operations provide a thread-safe way to make a copy of a shared pointer.
- Creating a copy means that when you change the global common pointer, your copy still points to the old line, so your code does not need to worry about the data that it uses changes when they do not expect it.
Now itβs important to note that using thread-safe operations in shared_ptr does not provide thread safety for the type it points to. You should always make sure that the object you are pointing to is used by a safe thread.