user2635088 user2635088 - 7 days ago 6
C++ Question

std::unordered_map<int32_t, int32_t> declared on heap

What is the syntax of declaring an std::unordered_map on the heap, performing some operations on it, and then freeing it? I'm doing:

std::unordered_map<int32_t, int32_t> *map_temp_last_close = new std::unordered_map<int32_t, int32_t>;
*(map_temp_last_close[val]) = *(int32_t*)(read_buffer + 30); //this happens multiple times in a loop
int32_t some_val = val * (*(map_temp_last_close[val]))
map_temp_last_close->clear();
delete(map_temp_last_close);


EDIT:
Why do I need to have it on the heap? I have an always running function that constantly receives data from the network and in certain cases, stores the data in a map to process it. Once the use of the map is over, I know that I will not receive that message in my protocol again and hence won't need the map, yet the map is not out of scope since the function is on an infinite loop (blocking when reading from the network). So I'd like to free up that memory by calling
free
or
delete
or something.

Answer

Your error was the positioning of the braces. You have to first de-reference and then index into the data structure.

I also would not put it on the heap in the first place, because std::unordered_map already stores its data on the heap internally, but if you really need to, the simplest and safest way I can think of is this::

auto map_temp_last_close = std::make_unique<std::unordered_map<int32_t, int32_t>>() 
(*map_temp_last_close)[val] = *(int32_t*)(read_buffer + 30); 
int32_t some_val = val * (*map_temp_last_close)[val]
//no need to manually delete or clear the map

This creates a std::unordered_map on the heap and a local unique_ptr variable that manages it: Whenever map_temp_last_close goes out of scope (be it via return, an exception or just because the current scope ends), it will automatically delete the map. Also, there is no reason to call clear prior to destruction, as the map will do that automatically.

Note:
Most likely (depending on the type of read_buffer) this expression: *(int32_t*)(read_buffer + 30) is undefined behavior.

Comments