3

可能重复:
返回受保护数据时如何使用 lock_guard

假设以下小班:

#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;
};

C++ 标准是否保证变量lockingetValues()在复制向量后被破坏?否则,此构造在线程代码中将是不安全的。

使用 g++ 4.4 进行实验,我看到以下测试程序导致了预期的结果:

#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;
}

输出:

Copied collection via copy constructor
Destroyed lock

这种行为是由 C++ 标准保证的,还是只是 g++ 行为?标准中的相关引用会很棒。

4

0 回答 0