簡體   English   中英

std :: unordered_map <int32_t, int32_t> 在堆上聲明

[英]std::unordered_map<int32_t, int32_t> declared on heap

在堆上聲明std :: unordered_map,對其執行一些操作然后釋放它的語法是什么? 我正在做:

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);

編輯:為什么我需要在堆上? 我有一個始終運行的功能,該功能不斷從網絡接收數據,在某些情況下,將數據存儲在映射中以進行處理。 一旦映射的使用結束,我知道我將不再在協議中接收到該消息,因此不再需要映射,但是由於函數處於無限循環中,因此該映射也不會超出范圍(從網絡讀取)。 因此,我想通過調用freedelete或其他方式釋放該內存。

您的錯誤是括號的位置。 您必須先取消引用,然后再索引到數據結構中。

我也不會一開始就將其放在堆上,因為std::unordered_map已經在內部將其數據存儲在堆上,但是如果您確實需要,我想到的最簡單,最安全的方法是::

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];

//map object will get destroyed automatically when map_temp_last_close goes out of scope, but if you want to delete it earlier, you can use:
map_temp_last_close.reset();

這會在堆上創建一個std::unordered_map和一個用於管理它的局部unique_ptr變量:每當map_temp_last_close超出范圍(通過返回,異常或僅由於當前范圍結束)時,它將自動刪除map 同樣,沒有理由在銷毀之前先調用clear ,因為地圖會自動進行clear

注意:
此表達式最有可能(取決於read_buffer的類型): *(int32_t*)(read_buffer + 30)是未定義的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM