I am trying to initialize a STL map using C++11 syntax but that doesn’t seem to work. After initialization, when i try to access the element, it tries to call the private constructor of Foo. Did I miss something? It works if I use at. I am wondering if I could use operator[] to access initialized values…
#include <map>
#include <string>
class Foo{
public:
int a, b;
Foo(int a_, int b_){
a = a_;
b = b_;
}
private:
Foo(){};
};
int main(){
std::map<std::string, Foo> myMap = { {"1", Foo(10,5)}, {"2", Foo(5,10)} };
int b = myMap["1"].b; // it tries to call private constructor of Foo.
return 0;
}
When you use the
operator[]on a map, you may use the operator to either get a value from the map or assign a value into the map. In order to assign the value into the map, the map has to construct an object of its value type, and return it by reference, so that you can useoperator=to overwrite an existing object.Consequently, the type has to be default constructible so that a new object can be created for you to assign into.
At run time, the constructor won’t be called if the key already exists, but the compiler has no way of knowing whether you’ll ever use
operator[]to access a value that doesn’t exist, so it requires the constructor to be public.