用静态变量初始化静态变量在c ++中得到了不同的结果

时间:2017-05-27 03:15:23

标签: c++ c++11 static

我正在使用c ++ 11编写程序,并且出现__static_initialization_and_destruction_0错误。所以我尝试编写一个小测试程序来提取问题部分并找出错误。这是我的测试程序:

在common.h文件中:

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

在common.cc文件中:

#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;

在main.cc文件中:

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

我的编译命令:g++ -std=c++11 main.cc common.cc

该程序没有出现__static_initialization_and_destruction_0错误,但结果让我更加困惑:

map_test:
1: 
2: 
3: 
value: 
found!
int_map_test:
1: 2
2: 4
3: 6
value: 4
found!

我得到了使用静态int变量初始化的预期静态映射,但它不能用于静态字符串变量。

为何与众不同?

顺便说一句,原始程序在__static_initialization_and_destruction_0定义行发生了map_test错误。

0 个答案:

没有答案