Re: pointer vs non-pointer
On Apr 22, 12:52 pm, worlman...@yahoo.com wrote:
On Tue, 22 Apr 2008 09:18:10 GMT, Your Name <n...@none.none> wrote:
Does limited scope means the object is only used in the
same function
"Scope" generally means "within the inner-most open/close
braces." For example, in C++ you can even do things like:
void func(int x, int z)
{
if (x == 5)
{
int y = x + 1;
y *= z;
}
y += 14; // (Compile error because "y" is out of scope here!)
}
So, if I want to return an object created in a function I
better use dynamic creation?
No. Why?
MyCar myfunction(){
MyCar mycar;
return mycar;
} // this is return by value
// this is more expensive as it copy whole value and return value
MyCar* myfunction(){
MyCar* mycar = new MyCar();
return mycar;
} // this is return by reference(pointer)
// less expensive as it only return 4 byte = pointer.
Maybe. If the program has a performance problem, and the
profiler says it is due to copying return values, you will have
to change to returning a pointer, probably with dynamic
allocation. (In that case, you should consider using something
like boost::shared_ptr.) Most of the tiem, however, it's not
really an issue, and the distinction is more one of whether the
object has identity or not. If it has identity, you can't
return by value. (And a pointer is 8 bytes on most of the
machines I work on.)
Also for a collection of object like a LinkedList object,
since it's very expensive to return by value, i must use
return by reference(pointer):
LinkedList* myfunction(){
LinkedList* list = new LinkedList();
return list;
} // this is return by reference(pointer)
This is a special case. First, I wouldn't worry about it any
more than the above until it was proven to be a performance
problem. (I once returned a linked list with some 60000
elements by value. Since the function was only called six times
in a program which otherwise took two or three hours to run, it
wasn't a problem.) If it does turn out to be a performance
problem, however, an alternative (and generally better) solution
is to have the caller provide the container, e.g.:
void
myFunction(
LinkedList& result )
{
result.clear() ;
// fill the list...
}
It's less convenient for the caller than return by value, but
still more convenient than having to handle a dynamically
allocated object.
But again, it's an optimization to be considered if, and only
if, you have a real performance problem.
// less expensive as it only return 4 byte = pointer.
// instead of return by value to copy all element in the List
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.
When are the times I must use dynamic creation ( create a pointer )?
One obvious case is when you actually want to create certain
things "dynamically." Suppose you're writing a game. When
the user clicks the mouse button, you want to make a gun fire
a bullet. You don't know at compile time how many times he
might press that button. You would need to create a new
"MyBullet" object every time he presses the button, and
probably "delete" the objects when they hit something, or
when they are far enough away that you can't see them any
more. You can't do that in a clean way without creating the
objects dynamically.
A common trick in the old days of C (and even before) was to
place a limit on the number of objects that could be created.
That's the reason, when you play "Galaga," that you can't
fire more than two bullets at a time. If you enforece a
limit like this, then you can declare your objects
statically:
MyBullet bullets[2];
And then when the user presses the "fire" button, you have to
check and make sure that at least one of the bullets has
already scrolled off the top of the screen. If it has, you
don't actually create anything, you just move the bullet
that's hiding just off the screen back to the tip of the gun
and start it going upward again.
There are certainly benefits to static allocation - speed
being a major one. There's also no possiblity of memory
leaks. There are lots of reasons to use dynamic allocation,
but it's never absolutely necessary. It just makes sense in
a lot of cases. It's usually kind of a balancing act.
In that case, if I used static object allocation, will it crash my
program?
In which case? If you don't know the number of objects up
front, you can't use automatic lifetime, at least not in the
end. Today, of course, you can get the same effect as automatic
lifetime by using things like std::vector---there is dynamic
allocation, but it all takes place under the hood, so to speak,
so you don't have to worry about it.
Will something like null pointer exception happens? as the
object get destroy automatically after function exit:
void myfunction(){
MyCar mycar = new MyCar();
Either this should be a pointer, or you shouldn't use new.
// mycar is used by other function also after function returns
mycar.AddEventListener();
// even myfunction returns,
// but mycar still need to listen for events
}
Objects with automatic lifetime end their lifetime at the end of
the scope in which they were created. If the object lifetime
must persist after this, and identity is important (and it is if
other objects have pointers to the object), then you must use
dynamic lifetime. Presumably, one of the "events", above, will
cause the object to self destruct, and the constructor will, of
course, ensure that all listeners are correctly informed, and
get rid of their pointers to the object. (In my own code, I'll
occasionally have things like:
new SomeObjectType ;
where I don't save the pointer resulting from the new
expression. The constructor of the object has registered itself
as an event listener somewhere, however, or in a map where it
can be found by looking up some external name, so the object
will be informed, and will delete itself correctly when the time
comes.)
--
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