code_junkie

When do function-level static variables get allocated/initialized?

Nov 10th, 2011
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. int globalgarbage;
  2. unsigned int anumber = 42;
  3.  
  4. void doSomething()
  5. {
  6. static bool globalish = true;
  7. // ...
  8. }
  9.  
  10. include <iostream>
  11. #include <string>
  12.  
  13. using namespace std;
  14.  
  15. class test
  16. {
  17. public:
  18. test(const char *name)
  19. : _name(name)
  20. {
  21. cout << _name << " created" << endl;
  22. }
  23.  
  24. ~test()
  25. {
  26. cout << _name << " destroyed" << endl;
  27. }
  28.  
  29. string _name;
  30. };
  31.  
  32. test t("global variable");
  33.  
  34. void f()
  35. {
  36. static test t("static variable");
  37.  
  38. test t2("Local variable");
  39.  
  40. cout << "Function executed" << endl;
  41. }
  42.  
  43.  
  44. int main()
  45. {
  46. test t("local to main");
  47.  
  48. cout << "Program start" << endl;
  49.  
  50. f();
  51.  
  52. cout << "Program end" << endl;
  53. return 0;
  54. }
  55.  
  56. global variable created
  57. local to main created
  58. Program start
  59. static variable created
  60. Local variable created
  61. Function executed
  62. Local variable destroyed
  63. Program end
  64. local to main destroyed
  65. static variable destroyed
  66. global variable destroyed
  67.  
  68. int foo(int i)
  69. {
  70. static int s = foo(2*i); // recursive call - undefined
  71. return i+1;
  72. }
  73.  
  74. int foo = init(); // bad if init() throws something
  75.  
  76. int main() {
  77. try {
  78. ...
  79. }
  80. catch(...){
  81. ...
  82. }
  83. }
  84.  
  85. int& foo() {
  86. static int myfoo = init();
  87. return myfoo;
  88. }
Add Comment
Please, Sign In to add comment