|
|
|---|
Basic C++ Programming
Static in C++
Normally, objects are placed on the stack. Memory is allocated by growing the stack at the top; thus objects are destroyed in the reverse order in which they are created. An object's life span is the same as its scope. If an object comes into scope more than once, then it is reinitialized each time, and destroyed when leaving its scope.
+----------+| || Heap | Allocated with new until deleted or program exits.| |+^^^^^^^^^^+| Stack | Local objects, parameters, temporaries, function return addresses.+----------+ +---------+| Data | <-- | Data | Initial values for static and global objects.+----------+ +---------+| Code | <-- | Code | Executable machine instructions.+----------+ +---------+ (Cannot be read or written by program.)| Reserved | a.out on disk| for OS || and other| Cannot be read or written by program, will cause segmentation| programs | fault or general protection fault.+----------+Memorystatic objects are placed in the data segment. They are initialized from values stored in the executable file, and therefore these values must be known at compile time. Initialization occurs only once. Values are maintained when the object is out of scope (e.g. between function calls), and it is safe to return a pointer or reference to them. Numeric values not explicitly initialized are set to 0.
int& f() { // Return by reference, f() is an alias for s, not a temporary copystatic int s=1; // Initialized only once++s;return s; // Safe to return by reference}int main() {cout << f(); // 2cout << f(); // 3f()=5; // OK, s=5;s=6; // Error, s is not in scoperegister
(Rare) A hint to the compiler to optimize an int or pointer for speed. It is no longer used because most optimizers can do a better job.
register int x;volatile
(Rare) Indicates that an object might be modified from outside the program (e.g. a hardware input port) and that the optimizer should not make copies of it. Its use is machine dependent.
const volatile unsigned short& port=*(const short*)0xfffe; // 16 bit port at address xfffeContents | Basic Concept|Statements| Expression |Declaration| Pointers| Arrays|Static
|Standard Library Type| Programing Organisation|History of C++ |
----------------------------------------You are Visitor No:
----------------------------------
------------------------------
------------------------------