3

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.

Community
  • 1
  • 1
tbleher
  • 1,077
  • 1
  • 9
  • 17
  • 1
    Not a quote, but generally the return value would have to be copied before starting to destruct local variables. Otherwise normal return by value wouldn't work either. – Bo Persson Oct 23 '12 at 07:57
  • Duplicate - Have a look at this [question](http://stackoverflow.com/q/8923018/220636) – nabulke Oct 23 '12 at 08:27
  • @Bo Persson: thanks, that's a useful heuristic to remember. – tbleher Oct 23 '12 at 08:38
  • @nabulke Thanks for the link - I didn't see that one when searching. Reading this answer, I'm surprised the C++ standard is so vague on this issue. – tbleher Oct 23 '12 at 08:40

0 Answers0