vendredi 26 mars 2021

Why I can't initialize a static const map in C++?

I want initialize a static const map in C++. But when I tried copy example to my code I got error like.

Code:

using namespace std;
struct A{     
static map<int,int> create_map()         
{           
map<int,int> m;           
m[1] = 2;           
m[3] = 4;           
m[5] = 6;           
return m;         
}     
static const map<int,int> myMap;
};
 
const map<int,int> A:: myMap =  A::create_map(); 

Error:

In function `std::numeric_limits<int>::min()':
multiple definition of `A::myMap'
first defined here
In function `void __gnu_cxx::new_allocator<std::_Rb_tree_node<std::pair<int const, int> > >::destroy<std::pair<int const, int> >(std::pair<int const, int>*)':
multiple definition of `A::myMap'
first defined here

I don't have a second definition anywhere. Could it be related to my compiler? After commenting the line below, the code builds

const map<int,int> A:: myMap =  A::create_map(); 

Aucun commentaire:

Enregistrer un commentaire