Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Elementary question on pointers

20 views
Skip to first unread message

Paul

unread,
Feb 10, 2020, 5:52:20 AM2/10/20
to
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.
(The author's point is that the code is bad style, not that it has any major
defects.)
Also, would it be ok to say cmplx z3 = *new cmplx(z+d); ?
Thanks a lot for your help,

Paul


void compute(cmplx z, double d)
{
cmplx z2 = z+d; // c++ style
z2 = f(z2); // use z2
cmplx& z3 = *new cmplx(z+d); // Java style (assuming Java could overload +)
z3 = f(z3);
delete &z3;
}

Paavo Helde

unread,
Feb 10, 2020, 6:27:17 AM2/10/20
to
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.
0 new messages