Here is a code sample:
class A {
boost::mutex a_mutex;
boost::shared_ptr<int> a;
boost::shared_ptr<int> clone_a(void) {
boost::lock_guard<boost::mutex> lock(a_mutex);
return a;
}
};
The suggestion is that the boost::shared_ptr copy constructor call on A::a will precede the boost::lock_guard destructor call despite of the compiler optimizations.
So, is it safe to call A::clone_a() ?
If by “safe” you mean you won’t get data races on
a, then yes. It is exactly as you say.However, it won’t protect further accesses to
*a(or*clone_a()), as you probably know. I’m not sure, why is the method called “clone”, as it doesn’t clone anything.