这个函数(运算符重载)线程是否安全?

时间:2011-03-13 13:38:16

标签: c++ multithreading operators

以下是代码:

ElementType& operator[] (int key)
{
    //something like boost::mutex::scoped_lock
    MutexLockType lock();

    if(key < 0 || key > m_bound)
        throw std::range_error("access out of bound");

    return m_elements[key];
}

2 个答案:

答案 0 :(得分:3)

不,不是因为你允许引用元素泄漏出函数并远离锁的安全性。

更重要的是,如果没有你最渴望的what flavour of thread-safety更难的规范,线程安全问题有点难以回答。至少,您需要向我们展示m_elementsm_bound的所有其他访问权限。

答案 1 :(得分:1)

在这个确切的例子中,当您意识到根本没有锁定时,您会更加惊讶,只是声明一个返回LockType的lock()函数。

不管怎样它都不会对锁有帮助。