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
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);
}