cpp: ex1: add solution

This commit is contained in:
Bruno BELANYI 2022-11-21 17:11:03 +01:00
parent c4a3886504
commit 8259ab1614

28
cpp/ex1.cc Normal file
View file

@ -0,0 +1,28 @@
#ifdef USE_ATOMIC_N
#include <atomic>
#endif
class CountInstances {
public:
CountInstances() {
++n_instances_;
}
~CountInstances() {
--n_instances_;
}
int nobjs() const {
return n_instances_; // If using atomics, load could use a more relaxed
// memory order, such as memory_order_acquire
}
private:
#ifdef USE_ATOMIC_N
// Can be used in a multi-thread program
static atomic<int> n_instances_;
#else
// Using a bare int mean races if used in a multi-threaded context
static int n_instances_;
#endif
};