11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 17: Making Constructive Arguments 235Executing this program generates the following results:Function fn passed a value of 10DoNothing constructed with a value of 10Function fn passed a value of 20Press any key to continue . . .Notice that the message from the function fn() appears twice, but the messagefrom the constructor for DoNothing appears only the first time fn() iscalled. This indicates that the object is constructed the first time that fn() iscalled, but not thereafter.All global objects construct before main()All global variables go into scope as soon as the program starts. Thus, allglobal objects are constructed before control is passed to main().Initializing global variables can cause real debugging headaches. Some debuggerstry to execute up to main() as soon as the program is loaded and beforethey hand over control to the user. This can be a problem because the constructorcode for all global objects has already been executed by the timeyou can wrest control of your program. If one of these constructors has afatal bug, you never even get a chance to find the problem. In this case, theprogram appears to die before it even starts!You can approach this problem in several ways. One is to test each constructoron local objects before using it on globals. If that doesn’t solve the problem,you can try adding output statements to the beginning of all suspectedconstructors. The last output statement you see probably came from theflawed constructor.Global objects constructin no particular orderFiguring out the order of construction of local objects is easy. An order isimplied by the flow of control. With globals, no such flow is available to giveorder. All globals go into scope simultaneously — remember? Okay, youargue, why can’t the compiler just start at the top of the file and work its waydown the list of global objects?That would work fine for a single file (and I presume that’s what most compilersdo). Unfortunately, most programs in the real world consist of several filesthat are compiled separately and then linked. Because the compiler has nocontrol over the order in which these files are linked, it cannot affect the orderin which global objects are constructed from file to file.

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

Saved successfully!

Ooh no, something went wrong!