D
Denis Remezov
jeffc said:Let's say you're in some function , and you want to accomplish some task x
that is provided for you by a class, A.
Which of these do you prefer, and is there a technical reason for it? (This
is actually the sort of thing that might be
provided for with a static class function, but one is not provided in this
case - an instance must be created.)
void f()
{
A a;
a.x();
A* p = new A();
p->x();
delete p;
A().x();
}
Normally, A().x(); No superfluous names. It is different from A a1; a1.x();
in that that the lifetime of a1 lasts until the end of the block; in the first
case, the object can (or shall? correct me on this if I'm wrong) be destructed
as soon as x(); returns. Which is something to keep in mind but normally should
be considered a bonus.
If there are reasons against A().x(); (style, maintainability, or
when the object must exist until the end of the block (e.g. we obtain and use
parts of it; I'm not delving into morality of that and the reasons why)), then
A a;
a.x();
Almost never this one:
A* p = new A();
p->x();
delete p;
which is longer to type, prone to misuse, typically less efficient and,
unless x() never throws, simply wrong.
[OT] I might consider the latter (corrected for the exception bug) if A
is extremely large and can cause problems with the stack reallocation
mechanism on a specific OS with a specific compiler, but this is exotic,
dubious and off-topic. [/OT]
Denis