错误:分配只读位置<unnamed> :: g_namesmap </unnamed>

时间:2011-01-27 12:15:36

标签: c++

我遇到了这个问题标题中提到的错误。代码段如下所示:

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是在未命名的命名空间中声明和定义的,为什么它被认为是“只读”?

1 个答案:

答案 0 :(得分:5)

因为您的地图data_type是使用const限定符声明的:

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

[]运算符与std::map一起使用时,它会返回与指定data_type值关联的key_type对象的引用。在这种情况下,您的data_typeconst size_t,因此您无法分配给它。

您需要将地图声明为:

std::map<std::string, size_t> g_namesmap;
相关问题