cpp: ex1: add solution
This commit is contained in:
parent
13348109d1
commit
4950125379
1 changed files with 28 additions and 0 deletions
28
cpp/ex1.cc
Normal file
28
cpp/ex1.cc
Normal 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
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue