0

There are two classes. Class A has a private member std::mutex m_. Class B has an instance of class A as its member.

The goal is to let class B to be able to use m_ (which is in class A).

I tried adding an accessor method in class A as below, but it gives error no matching function for call to 'std::unique_lock<std::mutex>::unique_lock(std::mutex)'.

  1. Is above error because std::mutex is non-copyable?
  2. What is the suggested way to expose the std::mutex in this case?
class A {
public:
    // does not work
    std::mutex getMutex() {
        return m_;
    }

private:
    std::mutex m_;
}

class B {
    A a;
    void someMethod() {
        ...
        std::unique_lock<std::mutex> lock(a.m_);
        ...
    }
}
2
  • I think, you might want to ask yourself why are you making mutex private, but want to expose. Those two are mutually exclusive from architecture point of view.
    – SergeyA
    Feb 9, 2021 at 22:57
  • @SergeyA Thanks for raising the question. In this case, there's a data structure in class A that's modified by 2 threads: one spawned in A, another spawned in B. Therefore, in order for the data structure to be used safely, A/B need to share that mutex. Since the mutex lives in A, class B needs to access it somehow.
    – kgf3JfUtW
    Feb 9, 2021 at 23:13

1 Answer 1

2

Is above error because std::mutex is non-copyable?

That is correct. A std::mutex cannot be copied or moved.

What is the suggested way to expose the std::mutex in this case?

In this case, you can just return by reference like

std::mutex& getMutex() {
    return m_;
}

and use it like

std::unique_lock<std::mutex> lock(a.getMutex());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.