I was trying to implement a boolean that can be atomically flipped. The suggestion on Stack Overflow is to use an integer. This would be my implementation.
#include <atomic>
#include <iostream>
class flippable_atomic_bool {
std::atomic<int> state;
public:
flippable_atomic_bool() : state(0){}
explicit flippable_atomic_bool(bool init) : state(static_cast<int>(init)) {}
explicit flippable_atomic_bool(const flippable_atomic_bool& other) = default;
flippable_atomic_bool& operator =(const flippable_atomic_bool& other) = default;
void flip() {
state ^= static_cast<int>(true);
}
operator bool() const {
return static_cast<bool>(state);
}
};
int main() {
{
flippable_atomic_bool a(true);
std::cout << static_cast<bool>(a) << std::endl;
a.flip();
std::cout << static_cast<bool>(a) << std::endl;
}
{
flippable_atomic_bool a{false};
std::cout << static_cast<bool>(a) << std::endl;
a.flip();
std::cout << static_cast<bool>(a) << std::endl;
}
}
1 0 0 1