[英]accessing operator overloading of class which is wrapped by std::shared_ptr
[英]calloc / malloc wrapped by std::shared_ptr
我有一些代碼包含使用calloc和malloc進行內存分配的自制哈希表。 我想使用shared_ptr和自定義刪除程序來修改這些部分,該刪除程序會自動釋放分配的內存。 該代碼是mmseg中文分段器算法的一部分,雖然效果很好,但由於它會導致內存泄漏而變得一團糟。 我正在考慮使用unordered_map等重寫該代碼,但現在我想進行這些更改。
我閱讀了類似問題的答案,例如帶有malloc和free的shared_ptr或通過shared_ptr訪問calloc'd數據 ,但是在下面的代碼上使用它存在問題。
我在這些行中無法使用智能指針包裝調用。 所以也許有人可以幫我解決這個問題:
struct Word {
unsigned char nbytes; /* number of bytes */
char length; /* number of characters */
unsigned short freq;
char text[word_embed_len];
};
struct Entry {
Word *word;
Entry *next;
};
static Entry **new_bins = static_cast<Entry **>(std::calloc(init_size,
sizeof(Entry *)));
Entry *entry, ...;
...
new_bins[hash_val] = entry;
....
free(new_bins);
上面的calloc調用我將用calloc的結果提供給共享指針,例如
std::shared_ptr<Entry *> binsPtr(new_bins, freePtr());
我不知道這是否正確。
mmseg使用帶有malloc()的池分配例程,如下所示:
inline void *pool_alloc(int len) {
void *mem = _pool_base;
if (len <= _pool_size) {
_pool_size -= len;
_pool_base += len;
return mem;
}
_pool_base = static_cast<char *>(std::malloc(REALLOC_SIZE));
mem = _pool_base;
_pool_base += len;
_pool_size = REALLOC_SIZE - len;
return mem;
}
然后將分配器稱為:
Entry *entry = bins[h];
...
entry = static_cast<Entry *>(pool_alloc(sizeof(Entry)));
entry->word = word;
entry->next = NULL;
bins[h] = entry;
是否可以修改pool_alloc例程,例如我可以使用共享指針包裝malloc()並定義自定義刪除器(甚至可以跳過完整的pool_alloc fct並僅使用shared_ptr),例如
std::shared_ptr<Entry> entry((Entry *)malloc(sizeof(Entry)), freePtr());
struct freePtr {
void operator()(void* x) {
free(x);
}
};
如果有人可以幫我解決這個問題,那就太好了。 提前致謝!
更新:
我為我的問題編寫了一個簡單的內存池類,因此所有指針都會自動銷毀。 shared_ptr中的包裝的calloc()似乎工作正常,並且按預期方式工作。 Valgrind報告不再有內存泄漏和錯誤。
OP寫道:
我為我的問題編寫了一個簡單的內存池類,因此所有指針都會自動銷毀。 shared_ptr中的包裝的calloc()似乎工作正常,並且按預期方式工作。 Valgrind報告不再有內存泄漏和錯誤。
換句話說,更改代碼可修復錯誤。 :)現在可以安全地刪除此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.