Game Development Reference
In-Depth Information
objects from a disk, a memory stream, or even the network. If you want to load game
objects from a disk, as you would in a save game, this is exactly how you do it.
Some programmers try to do stream initialization inside an object
'
s constructor:
AnimationPath (InputStream & stream);
Here
'
s why this is a bad idea
a bad stream will cause your constructor to fail, and
you
ll end up with a bad object. You can never trust the content of a stream. It could
be coming from a bad disk file or hacked network packets. Ergo, construct objects
with a default constructor you can rely on and create initialization methods for
streams.
'
Exercise Your Load/Save System
Test your stream initializers by loading and saving your game automatically in
the DEBUG build at regular intervals. It will have the added side effect of
making sure that programmers keep the load/save code pretty fast.
Smart Pointers and Naked Pointers
All smart pointers wear clothing.
If you declare a pointer to another object, you
ve just used a naked pointer. Pointers
are used to refer to another object, but they don
'
'
t convey enough information. Any-
thing declared on the heap must be referenced by at least one other object, or it can
never be freed, causing a memory leak. It is common for an object on the heap to be
referred to multiple times by other objects in the code. A good example of this is a
game object like a clock. A pointer to the clock will exist in the game object list, the
physics system, the graphics system, and even the sound system.
If you use naked pointers, you must remember which objects implicitly own other
objects. An object that owns other objects controls their existence. Imagine a ship
object that owns everything on the ship. When the ship sinks, everything else is
destroyed along with it. If you use naked pointers to create these relationships, you
have to remember who owns who. Depending on the system, this might be perfectly
reasonable or nearly impossible. If you choose to use a naked pointer, make sure that
you know exactly who can access it and when, or you ' ll quickly find yourself going
down with the ship.
Smart pointers, on the other hand, hold extra information along with the address of
the distant object. This information can count references, record permanent or tem-
porary ownership, or perform other useful tasks. In a sense, an object controlled by a
smart pointer
knows
about every reference to itself.
 
 
Search WWH ::




Custom Search