In some of the unique_lock
constructors in C++11 one can pass some classes like a flag, i.e.
auto lock = std::unique_lock<std::mutex> lock(m, std::defer_lock);
where std::defer_lock
is defined as
struct defer_lock {}
Why is it done this way, and not with an enum?
I tried to apply this to a small code sample, but I couldn't get it compiling:
class A {};
void foo(A a) {}
int main() {
foo(A); // error: 'A' does not refer to a value
}
When I put the parentheses like foo(A());
it works, but I don't see the difference to the STL. Why does this behave differently there?
Using a different type to mark a certain operation rather than an enum
makes the choice of code path being taking a compile-time choice rather than a run-time choice. The implementations of the different functions can also be drastically different.
Actually, std::defer_lock
is not defined as you write, but as
constexpr std::defer_lock_t defer_lock = std::defer_lock_t();
That's why your version "mimicking" (badly) the standard library definition doesn't work; change your definition to eg.
struct A {} A;
and it will work. (or, try slightly more appealing struct A_t {} A
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With