Atomic enum or enum class


#1

I can't seem to make an Atomic enum or enum class, I get the error

Cannot initialize a member subobject of type 'volatile TheEnum' with an rvalue of type 'int'

when I declare a Atomic<TheEnum> as a member of a class. What seems to work is declaring it as

Atomic<TheEnum> theEnum = Atomic<TheEnum>(TheEnum::Value1);

But I'm not sure if this is intended to work. Also it is a shame I can't have an Atomic<bool>.

 

Any insights on this?


#2

Assuming this is a feasible route, you might be able to use std::atomic<>.


#3

Thanks, we do use C++11. Are there any differences in std::atomic and juce::Atomic?


#4

std::atomic allows for any trivially copyable type to be encompassed, while the juce::Atomic apparently only allows primitive 32bit and 64bit types.


#5

Yes, but std::atomic doesn't guarantee that it will use actual atomic CPU instructions, it could use a mutex internally if you use it with a large structure.


#6

std::atomic<enum> will compile just fine if you have a standard-compliant compiler.

In practice, on Intel platforms std::atomic<T> will be lock-free (no mutexes will be inserted internally) if T can be represented as a fundamental type not larger than 64 bit.

enum is always represented as a fundamental integer type internally. In practice, on all common platforms this will be an int (unless you specify otherwise using the enum class syntax).

Therefore, std::atomic<enum> is perfectly fine and will behave as a std::atomic<int>.

 


#7

Thanks, std::atomic it is for me then.

Question remains why juce::Atomic can't handle enums, and bools for that matter..


#8

It really just comes down to the extra code that would be needed to implement more types for juce::Atomic. But in the near future when we finally ditch C++03 support, the juce atomic class will become a tiny wrapper around std::atomic that we keep for compatibility with legacy code.

Certainly in your own codebases, if you're using C++11 then you should choose std::atomic!