我正在使用 glib 中的 GHashTable,我想通过键删除一个键值对。如 docs 中所述当调用 g_hash_table_remove()
时,您需要在动态分配时自行释放键和值。但是我如何获得指向 key 的指针以便释放它?
编辑:我考虑过使用 g_hash_table_new_full
但我对 GHashTable 的使用太小以至于我认为这有点矫枉过正。我宁愿手动释放 key 。
编辑:正如 Keine Lust 所指出的,g_hash_table_new_full
的性能应该不会降低。如果不需要,您还可以为其中一个销毁函数传递 NULL
。
最佳答案
在哈希表中删除条目时释放
相关数据的一种简单方法是将free
函数传递给g_hash_table_new_full
:
GHashTable = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
参数
hash_func: a function to create a hash value from a key
key_equal_func: a function to check two keys for equality
key_destroy_func: a function to free the memory allocated for the key used when removing the entry from the GHashTable, or NULL if you don't want to supply such a function.
value_destroy_func: a function to free the memory allocated for the value used when removing the entry from the GHashTable, or NULL if you don't want to supply such a function.
关于c - 获取对存储在 GHashTable 中的键的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45652771/