'C++ shared_ptr and mutex
I'm new to C++ and I have to following scenario:
main.cpp
#include "Foo.h"
#include "Bar.h"
int main() {
Bar bar{};
auto bar_ptr = std::make_shared<Bar>(bar);
for (int i = 0; i < 10; i++) {
Foo foo{bar_ptr};
}
return 0;
}
I want 10 Instances of Class Foo to share 1 Instance of Class Bar. Each Instance of Class Foo will run in a separate Thread. I want the shared Instance of Class Bar only to be accessed by one Instance of Foo at a time. That's why I wanted to add a std::mutex to Foo. This seems to conflict with std::mutex not being copyable/moveable. What is the correct way to use a mutex with a shared_ptr?
Foo.h
#include <memory>
#include <utility>
#include "Bar.h"
class Foo {
std::shared_ptr<Bar> bar_ptr;
public:
explicit Foo(std::shared_ptr<Bar> bar_ptr){
this->bar_ptr = std::move(bar_ptr);
}
};
Bar.h
#include <mutex>
class Bar {
std::mutex mutex{};
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
