Style (or otherwise?) question: creating temporary to invoke function

A

Andrey Tarasevich

E. Robert Tisdale said:
...

Why should that make a difference?
...

What I meant to say is that it one cares to examine the internal state
of the 'A' object _after_ the operation, one has to declare a named
object of type 'A'. Otherwise, a temporary will do just fine.
 
I

Ioannis Vranos

David Harmon said:
On Sat, 17 Apr 2004 00:19:50 +0300 in comp.lang.c++, "Ioannis Vranos"


You would never allocate with 'new' for such a thing where you don't
even care about personally controlling the lifetime of the object. It
belongs only on the stack.


As i said to him: "Do the second if for some reason you can't do the first".
That means that for whatever reason he can't do the first (e.g. the object
does not fit in the stack), he should do the second.


And if for some reason it needed to be allocated with 'new', that would
still be wrong.


Then your general suggestion is never use new?


If x() throws an exception, the allocated object is
leaked. Horrors! If you must go this route, the minimum acceptable is

std::auto_ptr<A> p(new A);
p->x();


Relax. If A::x() can throw an exception he is supposed to catch it, else the
program will terminate anyway. And new has nothing to do with it.






Ioannis Vranos
 
I

Ioannis Vranos

Ioannis Vranos said:
Relax. If A::x() can throw an exception he is supposed to catch it, else the
program will terminate anyway. And new has nothing to do with it.


I do not like to work on assumptions, but if we assume that he uses many A
objects in many different places, and wants to catch the hypothetical
exception that A::x() throws, in some levels distance, he can use auto_ptr
as you suggested or some container.

But all these are assumptions, we have no information on what the OP is
actually doing.






Regards,

Ioannis Vranos
 
B

Benoit Mathieu

A* p = new A();
Leaving a reference lying around
to an object that should never be reference again
is an invitation for trouble.

I find it convenient to do the following to increase the
probability that the program will crash if the pointer is
used again...

delete p;
p = 0;

I also put the critical member variables to an invalid value
in the destructor when it is not too much time consuming (so
the program will more likely crash if there is a pointer to
this object somewhere else).

Other useful tricks ?

Benoit
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,158
Latest member
Vinay_Kumar Nevatia
Top