unordered_map

A short code before I proceed with problem:

class A
{public:
A(int input) : mem_var(input) { }
int mem_var;
};

int main() {
std::unordered_map<int, A> foo;
int k = 1;
A a(1);
foo[k] = a;
}

I am using g++ to compile and the above program gives an error saying I can't perform the operation: foo[k] = a;
It says that it needs a constructor of kind A(). When I do provide a default constructor then program compiles good. Any idea why we need a default constructor here.

On the side note, if I create a std::pair<int, A> object and call insert method, it works good even if there isn't any default constructor for A. Eg.
std::pair<int, A> testPair(k, a);
foo.insert(testPair);

I first found this behavior with boost::unordered_map<>. Later found that even std::unordered_map behaves in the same way. Anyone knows the exact reason for the above behavior. Thanks in advance.

It's because the operator [] has to construct a new a (using the default constructor) if the key hasn't been inserted yet. Then it returns a reference to that object.

Insert just copies the value of a over, using the copy constructor. (Which is implicitly defined for any class without an explicit copy constructor)
This is also the case with std::map.

If you instead use the at member function, foo.at(k) = a;, you would not have to have a default constructor, but if the key doesn't exist in the map it will throw an exception instead. That would force you to insert the element before you can access it.
Last edited on
Topic archived. No new replies allowed.