On 10.02.2020 12:52, Paul wrote:
> The below code snippet is from the
isocpp.org faq (as an example of bad style)
> cmplx& z3 seems to define a non-const reference to a temporary variable
> so I'm not sure why the cmplx& z3 definition is legal.
It's not a temporary. The keyword "new" means it's allocated dynamically
so it will live until explicitly deleted. One only has to make sure the
correct pointer value is passed to the 'delete' operator, which is done
properly in this example.
> (The author's point is that the code is bad style, not that it has any major
> defects.)
Yes, it's bad style. Also, if the f() function throws an exception,
there would be a memory leak as the 'delete' line would not be executed.
> Also, would it be ok to say cmplx z3 = *new cmplx(z+d); ?
> Thanks a lot for your help,
This is not ok as you now have an incurable memory leak (the address of
the dynamically allocated object is lost). Also, the current 'delete
&z3;' line would becomes UB because a wrong pointer is sent to it.