Beruflich Dokumente
Kultur Dokumente
Heap and stack use vary dynamically Code and global use is fixed Code segment is read-only
stack
stack
main crt0
Calculator * d
stack
main crt0
Calculator * d
Problem: object destroyed but Calculator c another alias to it was then used
Temporary variables
Are destroyed at end of statement Similar to problems w/ automatics
Important intuition
Incorrect use is the real problem here Need to understand the details
Temporary variables
Can be used throughout a statement But should not be referenced outside the statement where created Use the temporary variable to do output, etc. within a statement Use dynamic variables across scopes
Especially for use outside the creating stack frame
Example resolved
Automatic variables
Are scoped to the duration of the function in which they are declared
Global variables
Are scoped to the entire lifetime of the program Includes static class and namespace members May still have initialization ordering issues (more later: Singleton Pattern)
Member variables
Are scoped to the lifetime of the object within which they reside Depend on whether object itself is global, dynamic, automatic, temporary
Copyright 2002 Dept. of Computer Science and Engineering, Washington University
Resources allocated by an object need to be freed Constructor, destructor offer good start/end points Fixed stack calculator
Can push and pop ints Can add, etc. to top of stack Stack size may differ for each object Once set, stack size is fixed Notice the default parameter
Calculator initialization sets size, but zeroes out the pointer why? Test Only allocate if length is greater than zero Could also use conditional operator at initialization:
values_ (s > 0 ? new int [s] : 0)
Guard idiom revisited C++ has an auto_ptr class template auto_ptr<X> assumes ownership of a pointer-to-X auto_ptr destructor calls delete on the owned pointer Call release to break ownership by auto_ptr when its safe to do so
reference
Readers all share a copy, each writer can get its own
Copyright 2002 Dept. of Computer Science and Engineering, Washington University