Re: pointer vs non-pointer
On Apr 22, 10:52 am, worlman...@yahoo.com wrote:
For pointer and non-pointer initialization of an object like
MyCar mycar;
MyCar* mycar = new MyCar();
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's more complex than that. In general, if you have an object
with identity and an arbitrary lifetime, you need dynamic
allocation. You also need dynamic allocation if the type or
size aren't known at compile time.
If you don't need dynamic allocation, you shouldn't use it. If
the objects don't have identity, for example, you should prefer
returning a copy of it to returning a pointer to a dynamically
allocated instance.
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
}
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
}
Don't confuse scope with object lifetime. An object with
automatic lifetime does disappear when it last goes out of
scope, but as long as it exists, it can be used even in places
where it isn't in scope, e.g. because you've passed a pointer or
a reference to it.
Scope concerns the name, not the object, and defines where the
name is visible. Dynamic allocation or not concerns lifetime,
when the object is created and when it is destructed.
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.
Attention: static lifetime is still another thing. Objects
defined at namespace scope, or with the keyword static, have
static lifetime. Objects defined at local scope without the
keyword static have automatic lifetime. Objects created with a
new expression have dynamic lifetime. Temporaries and
exceptions have special lifetimes of their own.
In general, the compiler will manage both the lifetime and the
memory in all cases but dynamic lifetime. If one of the
compiler managed lifetimes can be used, you definitely should
prefer it.
When are the times I must use dynamic creation ( create a
pointer )?
Typically, when an object has identity (and can't be copied),
and an explicit lifetime. Sometimes, however, because you don't
know the type or the number of objects at compile time (although
dynamic containers like std::vector mean that most of the time,
you don't need dynamic allocation even when you don't know the
number at compile time).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34