News for hackers. Stuff that matters.
Re:My favourite C++ footgun by dataflow on Wednesday June 23, 2021 @02:40AM (#27601492)
> As this hypothetical scenario depends on an exception being thrown

It doesn't.

Exercise for the reader: detect evaluation interleaving without exceptions.

> If your code throws so many exceptions that not freeing the memory allocated during that code point becomes a problem

It need not manifest itself as a mere memory leak.

Exercise for the reader: make something happen beside a memory leak.

Re:My favourite C++ footgun by OskarS on Wednesday June 23, 2021 @09:25AM (#27604286)
> It doesn't

Yes it does. Of course you can detect different evaluation orders using side effects, but the fact that evaluation order is unspecified isn't generally a problem: if you write code like `a() + b()` and a() and b() has side-effects that depend on the order they're evaluated in, that is just a bad way of writing code. In any language.

The point here is that the compiler is allowed to interleave subexpressions of the two different arguments which causes a memory leak in seemingly safe code. That is a very unreasonable thing for the compiler to do, which is why it is a footgun. But not that it can ONLY happen if the second function throws in between the construction of the object with "new" and the construction of the shared_ptr: if the second function doesn't throw an exception, the construction of shared_ptr is guaranteed to happen.

Incidentally: those "exercise for the reader" comments are incredibly obnoxious.

Re:My favourite C++ footgun by dataflow on Wednesday June 23, 2021 @11:51AM (#27605926)
> isn't generally a problem

generally is the key word here.

> if you write code like `a() + b()`

The code doesn't have to look like that. Add e.g. some arguments...