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);
编辑:
为什么我需要把它放在堆上?我有一个总是 运行 的函数,它不断地从网络接收数据,在某些情况下,将数据存储在地图中以进行处理。一旦地图的使用结束,我知道我不会再在我的协议中收到该消息,因此不需要地图,但地图并没有超出范围,因为函数处于无限循环中(阻塞时从网络读取)。所以我想通过调用 free
或 delete
或其他东西来释放内存。
你的错误是牙套的位置。您必须先 取消引用,然后索引 到数据结构中。
我一开始也不会把它放在堆上,因为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
超出范围时(通过 return,一个异常或仅仅因为当前作用域结束),它将自动删除映射。此外,没有理由在销毁之前调用 clear
,因为地图会自动执行此操作。
注:
很可能(取决于 read_buffer
的类型)这个表达式:*(int32_t*)(read_buffer + 30)
是未定义的行为。
在堆上声明一个 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);
编辑:
为什么我需要把它放在堆上?我有一个总是 运行 的函数,它不断地从网络接收数据,在某些情况下,将数据存储在地图中以进行处理。一旦地图的使用结束,我知道我不会再在我的协议中收到该消息,因此不需要地图,但地图并没有超出范围,因为函数处于无限循环中(阻塞时从网络读取)。所以我想通过调用 free
或 delete
或其他东西来释放内存。
你的错误是牙套的位置。您必须先 取消引用,然后索引 到数据结构中。
我一开始也不会把它放在堆上,因为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
超出范围时(通过 return,一个异常或仅仅因为当前作用域结束),它将自动删除映射。此外,没有理由在销毁之前调用 clear
,因为地图会自动执行此操作。
注:
很可能(取决于 read_buffer
的类型)这个表达式:*(int32_t*)(read_buffer + 30)
是未定义的行为。