Error: assigning read-only location <unnamed> :: g_namesmap

I meet the error mentioned in the title of this question. The code snippet is as follows:

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 is declared and defined in an unnamed namespace, why is it considered read-only?

+4
source share
1 answer

Since your data_type map is declared using the const classifier:

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

When you use the [] operator with 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 equal to const size_t , so of course you cannot assign to it.

You need to declare a card as:

 std::map<std::string, size_t> g_namesmap; 
+5
source

Source: https://habr.com/ru/post/1337305/


All Articles