Here is a version of your code which doesn’t break aliasing rules:
class Foo
{
public:
Foo() : userData(0L) { }
long userData;
};
void Destroy(Foo* pFoo)
{
if (--pFoo->userData <= 0)
{
delete pFoo;
}
}
int main()
{
int i = 0;
while (i < 10)
{
Foo* pFoo = new Foo();
pFoo->userData = 1;
Destroy(pFoo);
i++;
}
return 0;
}
You might want to rename userData
to something more meaningful, e.g. refCount
.
solved GCC compiler wrong optimization