Possible Duplicate:
How to use lock_guard when returning protected data
Assuming the following small class:
#include <boost/thread.hpp>
#include <vector>
class ThreadSafeIntCollection {
public:
void add(int value) {
boost::mutex::scoped_lock lock(mMutex);
mVector.push_back(value);
}
std::vector<int> getValues() const {
boost::mutex::scoped_lock lock(mMutex);
return mVector;
}
private:
mutable boost::mutex mMutex;
std::vector<int> mVector;
};
Does the C++ standard guarantee that the variable lock
in getValues()
is destructed after the copying of the vector? Otherwise this construct would be unsafe in threaded code.
Experimenting using g++ 4.4, I see that the following test program leads to the expected result:
#include <iostream>
struct Collection {
Collection() {}
Collection(const Collection & /*other*/) {
std::cout << "Copied collection via copy constructor\n";
}
Collection operator=(const Collection & /*other*/) {
std::cout << "Copied collection via operator=\n";
return Collection();
}
};
struct Lock {
~Lock() {
std::cout << "Destroyed lock\n";
}
};
class SynchronizedClass {
public:
Collection getElements() {
Lock l;
return c;
}
private:
Collection c;
};
int main( int /*argc*/, const char* /*argv*/[] ) {
SynchronizedClass s;
Collection c = s.getElements();
return 0;
}
Output:
Copied collection via copy constructor
Destroyed lock
Is this behaviour guaranteed by the C++ Standard, or is this just g++ behaviour? A relevant quote from the standard would be great.