QuestionC
QuestionC

Reputation: 10064

When does std::map call the constructor for the mapped type?

If I have a container like this....

std::map <std::string, IHaveAReallyExpensiveConstructor_t>

Am I guaranteed that the constructor IHaveAReallyExpensiveConstructor_t() will only be called whenever I create a new element in the map, say with std::map::operator[]?

If it matters, only default construction is hard. Copy construction is cheap and not really a concern.

Upvotes: 2

Views: 1350

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254461

In C++11, operator[] is the only operation on std::map which requires mapped_value to be default constructible; so that is the only operation which could default-construct a value. emplace will also default-construct a value if you don't provide any constructor arguments.

If your implementation doesn't conform with C++11, then there's no guarantee that other operations won't construct a value; but no reason why any sane implementation would.

Upvotes: 5

ravi
ravi

Reputation: 10733

There are 2 cases for this:-

my_map[key] = value

1) If key is not in the map then copy constructor of "value" would be called to make a copy of that object in map.

2) If key is already present in the map, then there will be call to assignment operator of that object.

Upvotes: 0

Related Questions