11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

122Part II: Becoming a Functional C++ Programmerof dLocalVariable is returned from child(), it refers to a variable that nolonger exists. The memory that dLocalVariable formerly occupied is probablybeing used for something else.This error is very common because it can creep up in a number of differentways. Unfortunately, this error does not cause the program to instantly stop.In fact, the program may work fine most of the time — that is, the programcontinues to work as long as the memory formerly occupied bydLocalVariable is not reused immediately. Such intermittent problems arethe most difficult ones to solve.Providing a solution using the heapThe scope problem originated because C++ took back the locally definedmemory before the programmer was ready. What is needed is a block ofmemory controlled by the programmer. She can allocate the memory andput it back when she wants to — not because C++ thinks it’s a good idea.Such a block of memory is called the heap.Heap memory is allocated using the new command followed by the type ofobject to allocate. For example, the following allocates a double variable offthe heap.double* child(void){double* pdLocalVariable = new double;return pdLocalVariable;}Although the variable pdLocalVariable goes out of scope when the functionchild() returns, the memory to which pdLocalVariable refers doesnot. A memory location returned by new does not go out of scope until it isexplicitly returned to the heap using a delete command:void parent(void){// child() returns the address of a block// of heap memorydouble* pdMyDouble = child();// store a value there*pdMyDouble = 1.1;// ...

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!