| |
 | Forcing Object Allocation on the Free-store
By Danny Kalev, C++ Pro
|
C++ inherited the three storage types of C, namely automatic storage (also known as "stack memory"), static storage and the free-store, or the heap, in C parlance. In general, programmers are free to allocate objects and data variables on any of these three storage regions. However, some environments, design patterns, and frameworks impose restrictions on the storage type of objects. For instance, some environments do not support all three storage types (embedded systems for example have a very limited stack space so users can't allocate storage there). Some systems have a garbage collector that recycles only heap memory; therefore, programmers are often required to allocate objects only on the free-store. Finally, component-based architectures use uniform methods for creating and destroying objects that mandate the use of heap memory exclusively. Any of these scenarios will force you to allocate objects and data variables on the free-store exclusively.

C++ doesn't offer a direct construct to restrict object allocation to a specific storage type. How can you ensure that users don't create objects of a certain class on the stack or in static memory?

Declare the class's so-called special member functions as nonpublic members and define additional construction and destruction member functions.
|
|
Find Out More
All DevX 10-Minute Solutions for C/C++
DevX 10-Minute Solution: Overriding New and Delete
DevX 10-Minute Solution: Constructing an Object at a Pre-Determined Memory Position
DevX Tip Library: The Correct Syntax for Automatic Object Instantiation
DevX Tip Library: Properties of Static Storage
DevX Tip Library: Heap or Free-Store?
DevX Tip Library: The Access Specifier of Special Member Functions
Borland's VCL Framework
 | TALK BACK |
Would you like to see a garbage collector becoming an integral feature of standard C++? How will this feature effect your design and implementation? What kind of impact will it have on debugging and testing?
 |
|