Skip to content

Instantly share code, notes, and snippets.

@cezheng
Last active August 10, 2016 13:22
Show Gist options
  • Select an option

  • Save cezheng/f66246f0d2d227c5073e21973443e459 to your computer and use it in GitHub Desktop.

Select an option

Save cezheng/f66246f0d2d227c5073e21973443e459 to your computer and use it in GitHub Desktop.
C++11 behaviour memo

Scoped static variable

Constructed the first time the program goes to the line of its declaration. Thread safe.

#include <iostream>

class A {
public:
  A(int i) {
    std::cout<<"constructor"<<i<<std::endl;
  }
};

void test(bool shouldGoto) {
  static A a(1);
  {
    static A a(2);
    {
      static A a(3);
    }
    if (shouldGoto) {
      goto jump;
    }
    static A aa(4);
    {
      static A a(5);
    }
  }
  static A aa(6);
jump:
  static A aaa(7);
}

int main(int argc, const char * argv[]) {
  test(true);
  test(false);
  return 0;
}
constructor1
constructor2
constructor3
constructor7
constructor4
constructor5
constructor6

Reserve std::vector before pushing elements

Bad example

std::vector<int> v;
// vector might resize itself several times, each time copying all existing elments
// if element type is a large class, the overhead would be horrible 
for (int i = 0; i < n; i++) {
  v.push(i);
}

Good example

std::vector<int> v;
v.reserve(n);
for (int i = 0; i < n; i++) {
  v.push(i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment