2011-01-27 41 views
4

我遇到了此问题标题中提到的错误。该代码片段看起来是这样的:错误:分配的只读位置<unnamed> :: g_namesmap

namespace 
{ 
    struct myOptVar * g_optvar = 0; 

    //Variable that stores map of names to index 
    std::map<std::string, const size_t> g_namesmap; 
}; 

void Optimizations::generate() 
{ 
    // free current optvar structure 
    free(g_optvar); 

    //clear our names map 
    g_namesmap.clear(); 

    // create new optvar structure 
    const unsigned int size = g_items.size(); 
    g_optvar = (struct myOptVar*)calloc(size, sizeof(struct myOptVar)); 

    //copy our data into the optvar struct 
    size_t i=0; 
    for (OptParamMapConstIter cit=g_items.begin(); cit != g_items.end(); cit++, i++) 
    { 
     OptimizationParameter param((*cit).second); 
     g_namesmap[(*cit).first] = i; //error occurs here 

    ... 

g_namesmap声明,并在未命名的命名空间中定义,它为什么认为是“只读”?

回答

5

因为你的地图data_type声明与const预选赛:

std::map<std::string, const size_t> g_namesmap; 

当您使用[]运营商与std::map,它返回到与指定key_type值相关联的data_type对象的引用。在这种情况下,你的data_typeconst size_t,所以当然你不能指定它。

你需要在地图声明为:

std::map<std::string, size_t> g_namesmap;