开发者

error: assignment of read-only location <unnamed>::g_namesmap

I am encountering the error mentioned in the title of this question. The code snippet looks like this:

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++ )
    {
        O开发者_开发知识库ptimizationParameter param((*cit).second);
        g_namesmap[(*cit).first] = i;  //error occurs here

    ...

g_namesmap is declared and defined in the unnamed namespace, why is it considered 'read only'?


Because your map data_type is declared with the const qualifier:

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

When you use the [] operator with an std::map, it returns a reference to the data_type object associated with the specified key_type value. In this case, your data_type is const size_t, so of course you can't assign to it.

You need to declare the map as:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜