开发者

Is this function(operator overloading) threadsafe?

开发者 https://www.devze.com 2023-02-16 18:09 出处:网络
Here\'s the code: ElementType& operator[] (int key) { 开发者_开发知识库//something like boost::mutex::scoped_lock

Here's the code:

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


No it is not because you have allowed a reference the element to leak out of the function and away from the safety of the lock.

What's more, thread-safety questions are a little hard to answer without a harder specification of just what flavour of thread-safety you are desirest. At the very least you would need to show us every other access of m_elements and m_bound.


In this exact example you would be even more surprised when you realize that there is no lock at all, just a declaration of a lock() function that returns a LockType.

Not that that it would have helped with a lock anyway.

0

精彩评论

暂无评论...
验证码 换一张
取 消