See:
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines...
and specifically, guidelines R.10, R.1 and R.3.
See also this answer:
https://stackoverflow.com/a/48046118/1593077
to the question of why C++ doesn't have a garbage collector.
To be more concrete, the example would be written today as:
{
auto foo = std::make_unique<Foo>();
}
foo->Process();
the last line won't compile - foo is gone already; and if you moved it inside the block scope, then foo would be valid.Now, the guidelines I mentioned can also be partially statically-checked, and some IDEs have begun to do so, so that the original snippet would give you at least 3 or 4 warnings. Interestingly, this will be true in a larger codebase as well, despite the claim in the article that
> UAFs are often hard to spot in larger codebases where ownership of objects is transferred between various components.
and that's because if you adhere to the coding guidelines _locally_, but throughout your application, including also I.11 about ownership transfer, then you can never free a pointer you don't own (unless you explicitly decide to do so), and you can even avoid dereferencing null pointers. Yes, I meant what I said: You can simply avoid ever dereferencing a null pointer.
All of this is supported by static analysis, so you absolutely don't need to be a virtuous and skilled coder to avoid such conundrums.
---
There's a caveat though: If some of the code is not under your control, but is rather some 3rd-party library or header, then what I said only applies if you properly "sanitize" at the boundaries of your well-checked.