520 pdfsam Cplusplus Primer Plus 4th Edition

This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks exte...

0 downloads 8 Views 3KB Size
This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks

extern void spoff(int); // use C++ protocol for name look-up extern "C++" void spaff(int); // use C++ protocol for name look-up The first uses C language linkage. The second and third use C++ language linkage. The second does so by default, and the third explicitly.

Storage Schemes and Dynamic Allocation You've seen the five schemes C++ uses to allocate memory for variables (including arrays and structures). They don't apply to memory allocated by using the C++ new operator (or by the older C malloc() function). We call that kind of memory dynamic memory. As you saw in Chapter 4, dynamic memory is controlled by the new and delete operators, not by scope and linkage rules. Thus, dynamic memory can be allocated from one function and freed from another function. Unlike automatic memory, dynamic memory is not LIFO; the order of allocation and freeing depends upon when and how new and delete are used. Typically, the compiler uses three separate memory chunks: one for static variables (this chunk might be subdivided), one for automatic variables, and one for dynamic storage. Although the storage scheme concepts don't apply to dynamic memory, they do apply to pointer variables used to keep track of dynamic memory. For example, suppose you have the following statement inside a function:

float * p_fees = new float [20]; The 80 bytes (assuming a float is four bytes) of memory allocated by new remains in memory until the delete operator frees it. But the p_fees pointer passes from existence when the function containing this declaration terminates. If you want to have the 80 bytes of allocated memory available to another function, you need to pass or return its address to that function. On the other hand, if you declare p_fees with external linkage, then the

p_fees pointer will be available to all the functions following that declaration in the file. And by using

extern float * p_fees; in a second file, you make that same pointer available in the second file. Note, however, that a statement using new to set p_fees has to be in a function because static storage variables can only be initialized with constant expressions: