I have a class defined in the same file of main, another class(full of static functions/members) defined in 2 seperate files, and it crashes. I guess this may be relevant to the lifetime of global/static instance. it seems that in the ctor, the static member has not been initialized, and it may happends that when exit, the static member is freed before the first instance is destructed. here is the test code:
//testh.h
#include <map>
class Sc {
public:
static void insert();
static void out();
private:
static std::map<int, int> map_;
};
//testcpp.cpp
#include "testh.h"
#include <iostream>
std::map<int, int> Sc::map_;
void Sc::insert() {
map_.insert(std::make_pair(2,3));
}
void Sc::out() {
for(auto m : map_) {
std::cout << m.first << ' ' << m.second << '\n';
}
}
//main.cpp
#include "testh.h"
class Nc {
public:
Nc() {
Sc::insert();
Sc::out();
}
~Nc() {
Sc::insert();
Sc::out();
}
};
Nc nc;
int main() {
system("pause");
return 0;
}
here are some strange behaviours of the above code:
if I replace the staic member to int, it will not crash, so I suppose there may be problems with std::map?
if I put all the codes into main.cpp, it will not crash, but wouldn't these generates the same codes?
how to solve this problem if I don't want to do dynamic allocation(new)?