Is it safe to return the value of shared_ptr, which is protected by the mutex?

Here is a sample code:

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; } }; 

It is assumed that a call to the boost::shared_ptr constructor on A::a will precede a call to the boost::lock_guard , despite optimizing the compiler. So, is it safe to call A::clone_a() ?

+4
source share
3 answers

If โ€œsafeโ€ means that you will not get data rockets on a , then yes. It is exactly the same as you say.

However, it will not protect further access to *a (or *clone_a() ), as you probably know. I'm not sure why the method is called โ€œcloneโ€, because it does not clone anything.

+5
source

Yes, this code is safe. If you refer to shread_ptr Thread-Safety , you can see that thread-local access to thread-local shared_ptr objects is just fine.

In your code above, accessing the shared_ptr member requires locking, as it can be accessed by multiple threads. A return copy is temporarily held inside the castle, so you are safe there. This temporary cannot be seen by other threads, so at this point you can copy it to other shared_ptr.

Now, perhaps, choosing clone_a as the function name is incorrect. You are not cloning the base object, you are just getting a copy of shared_ptr. Therefore, I assume that you intend to use the same basic "int".

+2
source

Not if you use the return value. The return value itself is temporary, whose lifetime is beyond the scope of the function; This will be destroyed at the end of the full expression that calls A::clone_a . Therefore, if you write something like:

 shared_ptr<int> newA = object->clone_a(); 

formal semantics will be to temporarily return object->clone_a() to copy to newA , in the context of the caller (and therefore not protected by the mutex). In this particular case, you may get away from it because of the RVO, but it will not necessarily be and there are other cases when the RVO cannot intervene.

If all that bothers you is a copy of the pointer, I am sure that if you set the correct compiler options ( -D somthing ), boost::shared_ptr will behave atomically. In this case, you donโ€™t need a mutex at all.

-1
source

All Articles