Re: pointer vs non-pointer
F,up to microsoft.public.vc.language, this has nothing to do with MFC.
worlman385@yahoo.com wrote:
For pointer and non-pointer initialization of an object like
MyCar mycar;
MyCar* mycar = new MyCar();
Note: the parentheses are not necessary in the second form.
I heard from other people saying if object i create must live outside
scape, then I use pointer version, else if only use object for a
limited scope, then use non-pointer version.
It depends on what type of object it is. There are objects that behave like
values (std::string, float etc) and others that behave like entities
(std::fstream, CWnd etc). Value types can be copied and so can be returned
from functions. The original object only lives inside the function, but its
value is transferred to the caller in a copy. Entity types can not be
copied, so if you need to return them from a function, you have to allocate
them dynamically.
Note that there is a subgroup of value types and that is values that are
indeed copyable but expensive to copy. Those are e.g. containers with many
elements. Being able to make this distinction can't be generalised though,
you have to look at the program in question.
Does limited scope means the object is only used in the same function
like:
void myfunction(){
MyCar mycar;
// mycar is only used inside this function
}
This means that mycar's destructor is called when the function is left (via
[implicit] return or exception).
and if mycar is used by outside scope means:
void myfunction(){
MyCar* mycar = new MyCar();
// mycar is used by other function also after function returns
mycar->AddEventListener();
// even myfunction returns,
// but mycar still need to listen for events
}
In this case, you have no choice but to create a MyCar object that still
exists after this function exits, so you need dynamic allocation. Note that
in theory, objects of static duration (globals, function-static,
class-static) could work, too, but are not as flexible.
I most case, I would perfer to use the static object creation:
MyCar mycar;
since I don't need to worry about delete / free object after creation.
Right, and you named the exact reasons. However, two techniques have been
invented that actually help with this:
1. garbage collection
2. smart pointers
When are the times I must use dynamic creation ( create a pointer )?
Do it when you must. Otherwise, prefer not to.
Uli
--
C++ FAQ: http://parashift.com/c++-faq-lite
Sator Laser GmbH
Gesch??ftsf??hrer: Michael W??hrmann, Amtsgericht Hamburg HR B62 932