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]))
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.
Most likely (depending on the type of
read_buffer) this expression:
*(int32_t*)(read_buffer + 30) is undefined behavior.