I have a very similiar question asked already 2012.
Critical Sections and return values in C++
I'd like to access a container thread safe aswell but instead return a cached version by reference.
struct Container {
const Data& getSomeData() const {
EnterCriticalSection(& myCritSec);
if (update) {
cache.calulatefromcontainer();
}
// fill retobj with data from structure
LeaveCriticalSection(& myCritSec);
return cache;
}
private:
mutable Data cache;
};
The problem is, that "return cache" line isn't protected anymore. Is it possible to return "cache" thread safe by reference?