Because C++ objects are often allocated from the heap and have limited
scope, memory use affects performance more in C++ programs than it does in C
programs. For that reason, consider the following guidelines when you
develop C++ applications:
- In a structure, declare the largest members first.
- In a structure, place variables near each other if they are frequently
used together.
-
Ensure that objects that are no longer needed are freed or otherwise made
available for reuse. One way to do this is to use an object
manager. Each time you create an instance of an object, pass the
pointer to that object to the object manager. The object manager
maintains a list of these pointers. To access an object, you can call
an object manager member function to return the information to you. The
object manager can then manage memory usage and object reuse.
- Storage pools are a good way of keeping track of used memory (and
reclaiming it) without having to resort to an object manager or reference
counting.
-
Avoid copying large, complicated objects.
-
Avoid performing a deep copy if a shallow copy is all
you require. For an object that contains pointers to other objects, a
shallow copy copies only the pointers and not the objects to which they
point. The result is two objects that point to the same contained
object. A deep copy, however, copies the pointers and the objects they
point to, as well as any pointers or objects contained within that object, and
so on.
-
Use virtual methods only when absolutely necessary.
