Why is a default constructor required when storing on a map?

I get an error message:

error: no matching function for call to 'A::A()' note: candidates are: A::A(const A&) note: A::A(const std::string&, size_t) 

From this:

 #include <map> #include <string> using std::map; using std::string; class A { public: string path; size_t size; A (const string& p, size_t s) : path(p), size(s) { } A (const A& f) : path(f.path), size(f.size) { } A& operator=(const A& rhs) { path = rhs.path; size = rhs.size; return *this; } }; int main(int argc, char **argv) { map<string, A> mymap; A a("world", 1); mymap["hello"] = a; // <----- here A b(mymap["hello"]); // <----- and here } 

Please tell me why the constructor without parameters wants the code.

+6
source share
4 answers

mymap["hello"] may try to create an initialized value A , so a default constructor is required.

If you use type T as the value of map (and plan to access the value through operator[] ), it should be the default - i.e. you need a parameter-less (default) constructor . operator[] on the map will value-initialize the displayed value if the value with the provided key is not found.

+3
source

Since map requires DefaultConstructible values, since no index and key were found using the index operator, it adds it to the default value.

+7
source

In general, the default constructor does not have a map element value.

This was required in C ++ 03, but this requirement was dropped in C ++ 11, which often instead of creating requirements in the container uses a finer-grained requirements scheme with requirements for using specific member functions.

map::operator[] is one of these member functions because it will create an element with the given key and default value if the element with the key does not exist.

This is also the reason why the const version of map::operator[] does not exist: it potentially modifies the map.

In C ++ 11 and later, you can use the at accessory to access an element with a given key on a const map without the granularity and complexity of find .

Since map::at does not attempt to create an element, it does not require the element type to be constructive by default.

So, one practical solution to your problem is to use map::at instead of map::operator[] .

+3
source

For a long time without using C ++, but if I call it correctly, if you do not define a constructor for the class, the compiler will create unlimited for you. Once you define a constructor with parameters, the compiler will not create unlimited for you, so you must create it. This is added to the fact that an open K-ballo leads to your errors.

+1
source

All Articles