I am using c++11 to writing a program, and I got __static_initialization_and_destruction_0
error. So I try to write a small test program to extract the problem part and find what's wrong. Here is my test program:
In common.h file:
#include <string>
class CommonUtil
{
public:
static const std::string STR_A;
static const std::string STR_B;
static const std::string STR_C;
static const int INT_A;
static const int INT_B;
static const int INT_C;
};
In common.cc file:
#include "common.h"
const std::string CommonUtil::STR_A = "A";
const std::string CommonUtil::STR_B = "B";
const std::string CommonUtil::STR_C = "C";
const int CommonUtil::INT_A = 2;
const int CommonUtil::INT_B = 4;
const int CommonUtil::INT_C = 6;
In main.cc file:
#include <map>
#include <iostream>
#include "common.h"
static const std::map<int, std::string> map_test =
{
{1, CommonUtil::STR_A},
{2, CommonUtil::STR_B},
{3, CommonUtil::STR_C}
};
static const std::map<int, int> int_map_test =
{
{1, CommonUtil::INT_A},
{2, CommonUtil::INT_B},
{3, CommonUtil::INT_C}
};
class Test
{
public:
bool IsItemInMap(int item);
bool IsItemInIntMap(int item);
};
bool Test::IsItemInMap(int item)
{
std::cout << "map_test:" << std::endl;
for (auto &p : map_test)
{
std::cout << p.first << ": " << p.second << std::endl;
}
if (map_test.find(item) != map_test.end())
{
std::cout << "value: " << map_test.at(item) << std::endl;
return true;
}
return false;
}
bool Test::IsItemInIntMap(int item)
{
std::cout << "int_map_test:" << std::endl;
for (auto &p : int_map_test)
{
std::cout << p.first << ": " << p.second << std::endl;
}
if (int_map_test.find(item) != int_map_test.end())
{
std::cout << "value: " << int_map_test.at(item) << std::endl;
return true;
}
return false;
}
int main()
{
Test test;
if (test.IsItemInMap(2))
{
std::cout << "found!" << std::endl;
}
else
{
std::cout << "not found!" << std::endl;
}
if (test.IsItemInIntMap(2))
{
std::cout << "found!" << std::endl;
}
else
{
std::cout << "not found!" << std::endl;
}
}
My compile command: g++ -std=c++11 main.cc common.cc
The program do not get __static_initialization_and_destruction_0
error but the result confuse me more:
map_test:
1:
2:
3:
value:
found!
int_map_test:
1: 2
2: 4
3: 6
value: 4
found!
I got the expected static map which is initialized with the static int variables, but it do not work with static string variables.
Why the difference?
By the way, the original program got __static_initialization_and_destruction_0
error at the map_test
defination line.
Aucun commentaire:
Enregistrer un commentaire