
From: "Howard Hinnant"
On Apr 24, 2004, at 2:04 PM, Peter Dimov wrote:
why are we trying to built thread-safety into shared_ptr? There is good saying that drove C++ to the point where we are right now: "do not pay for what you do not use". If I'm willing to provide own synchronization for shared pointers,
You can't. Not unless you control the entire program and you can determine with certainty which shared_ptr instances share ownership at every particular moment.
Actually I'm not convinced about this. I have the same concerns as Bronek. They are only concerns. I am not sure of myself. But here's a data point:
In the Metrowerks std::tr1::shared_ptr I give the option to the client whether or not shared_ptr contains a mutex (via a #define flag). This decision can be made independent of whether the entire C++ lib is compiled in multithread mode or not. And at the same time I use shared_ptr in the implementation of std::locale.
In the std::locale implementation I am careful to wrap each use of the locale implementation with a mutex lock. I believe I would have to do this whether or not shared_ptr protected its count. And yet std::locale is just a library, not an application.
I am not sure whether you can skip the count synchronization here. Even though you do not expose a shared_ptr directly, the user can still copy a std::locale at will. When two threads copy the same std::locale at the same time, a non-synchronized count leads to undefined behavior. Note that there's no mutex requirement. But you need the atomic updates.
Perhaps a more correct statement is that if you expose a shared_ptr as part of your interface, and advertise that multiple threads can operate on copies of that exposed shared_ptr, then shared_ptr must be internally protected.
It doesn't matter whether the user sees the shared_ptr or not. What matters is whether it can be copied by two threads (or copied by one thread and destroyed in another) at the same time. Which I believe is the case in your std::locale example. But I may be wrong because std::locale isn't one of my areas of expertise.