On Tuesday, 22 November 2022 at 00:46:34 UTC, Siarhei Siamashka
wrote:
..
The `counter` member variable isn't really protected from rogue
accesses (if these accesses are done by the code in the same
source file) and this behavior differs from C++.
module CounterTest;
//@concrete public synchronized class Counter // if only D
has this property.
public synchronized class Counter
{
static import core.atomic;
private:
int count = 0;
public:
void incrementCounter()
{
if ((count + 1) < 0)
{
// you might want to handle this
}
else
core.atomic.atomicOp!"+="(this.count, 1);
}
int displayCounter()
{
return count;
}
}
void main()
{
import std;
shared Counter c = new Counter;
for (int i = 0; i < 5; i++)
c.incrementCounter;
c.count = 0; // not if your class is a @concrete class
writeln(c.displayCounter);
}
unittest
{
shared Counter c = new Counter;
c.count = 0; // not if your class is a @concrete class
}