Say I have n different resources. Let's say n = 5 as an example, but n can be large and optionally an input value. I want to initialize a vector of n binary semaphores. How do I do that?
I believe the problem is because the constructor for binary_semaphore
or counting_semaphore
has been marked explicit
. I've tried the vector constructor for n objects of the same value, and also push_back
and emplace_back
, but nothing seems to work. Is there a way to solve this problem?
CodePudding user response:
Semaphores (along with many other mutex-like types... including mutex
) are non-moveable. You cannot put such a type in a vector
. This is not about explicit constructors; it's about the lack of a copy or move constructor.
Allocating an array of these is made difficult by the lack of a default constructor. You can try to work around this by wrapping the semaphore in a type that does have a default constructor, for which you would use some default count.
struct default_binary_semaphore
{
std::binary_semaphore sem; //Make it public for easy access to the semaphore
constexpr default_binary_semaphore() : sem (default_value) {}
constexpr explicit default_binary_semaphore(auto count) : sem(count) {}
};
Note that, while you can allocate arrays of this type, the type is still non-moveable.