Reputation: 315
If I have a std::map with default allocator that initialises to no element, will memory be allocated when it is defined to provide some capacity? Is there a way I can prevent the memory allocation until the first time an insertion is performed? I would like this behaviour because I need to frequently create a map, but it is often not used at all and thus no element is inserted. I would like to pay the cost of memory allocation only when an element is inserted.
i.e.
std::map<string, double> foo{}; // Is there memory allocation here?
Upvotes: 2
Views: 864
Reputation: 40901
A more detailed answer to a similar question can be found here: https://stackoverflow.com/a/57299732/5754656
What an empty / default constructed map is isn't mandated by the standard. Most have their internal pointers point to some "end node". In libc++ and libstdc++, this end node is not heap allocated, and the default constructor is marked noexcept
(and there is no allocation, as you want). In Microsoft's standard library, the end node is on the heap and there would be memory allocation.
The only way to prevent memory allocation if not used is to not call the default constructor. This could mean using alternative map implementations or using a std::optional<std::map>
or something else
Upvotes: 3