I have a question that is related to, but not answered by, this question:
Example for boost shared_mutex (multiple reads/one write)?
I understand how the exclusive locks work when the operations are scoped within the member function. My question is, what about return-by-reference functions? Consider the following (psuedo-code):
class A {
shared_mutex _mutex;
std::string _name;
public:
const std::string& name() const {shared_lock(_mutex); return _name;}
}
Then assume I do something like this in code:
A obj;
if (obj.name().length() >0) { ... };
My gut tells me this may not be thread safe, since the mutex will already have gone out of scope by the time the length() function is called, but I don't know.
I guess I'm also asking in the big picture, if I'm trying to make the object thread-safe, should I avoid returning by reference altogether? Wouldn't it enable someone to do something like this:
A obj;
std::string& s = obj.name();
(at this point lock is out of scope)
s = "foo"; // does this change the original object's member since it is a reference?