The definitions for std::atomic<> seem to show its obvious usefulness for primitive or perhaps POD-types.
When would you actually use it for classes?
When should you avoid using it for classes?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The operations
std::atomicmakes available on any trivially copyable type are pretty basic. You can construct and destroyatomic<T>, you can ask if the typeis_lock_free(), you can load and store copies ofT, and you can exchange values ofTin various ways. If that’s sufficient for your purpose then you might be better off doing that than holding an explicit lock.If those operations aren’t sufficient, if for example you need to atomically perform a sequence operations directly on the value, or if the object is large enough that copying is expensive, then instead you would probably want to hold an explicit lock which you manage to achieve your more complex goals or avoid doing all the copies that using
atomic<T>would involve.As you can see, this basically gets a copy of the value, modifies the copy, then tries to copy the modified value back, repeating as necessary. The modifications you make to the copy can be as complex as you like, not simply limited to single member functions.