我有一個相關的問題,但不是,這個問題回答共享互斥與回報:C++參考
Example for boost shared_mutex (multiple reads/one write)?
我明白了排它鎖是如何工作的,當操作中的作用域成員函數。我的問題是,通過引用返回函數呢?考慮以下(僞代碼):
class A {
shared_mutex _mutex;
std::string _name;
public:
const std::string& name() const {shared_lock(_mutex); return _name;}
}
然後假設我做這樣的事情代碼:
A obj;
if (obj.name().length() >0) { ... };
我的直覺告訴我,這可能不是線程安全的,因爲互斥體已經具有在length()函數被調用的時候超出了範圍,但我不知道。
我想我也在問大圖片,如果我試圖讓對象線程安全,應該避免通過引用完全返回?那豈不是讓別人做這樣的事情:
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?
由於您提到的懷疑,它不是**線程安全的。返回副本而不是參考將是一個可行的解決方案。 – 2013-03-25 20:26:38
@Drew Dormann,是否簡單地從返回值中刪除引用運算符強制它返回一個副本,還是編譯器仍然可以優化它作爲引用? – amnesia 2013-03-25 20:36:40