使用unique_ptr和gsl_vector [英] Using unique_ptr with gsl_vector
问题描述
unique_ptr
我最喜欢的一个方面是它提供的自动内存管理。我想用类似GSL向量的 unique_ptr
。
One of my favorite aspects of unique_ptr
is the automatic memory management it provides. I would like to use unique_ptr
with something like a GSL vector.
但是, gsl_vector
有自己的释放内存的机制( gsl_vector_free
)。有没有办法强制唯一的指针使用GSL的向量释放方法?在下面创建 unique_ptr< gsl_vector>
时,Valgrind(正确)报告malloc / delete的不匹配使用:
However, gsl_vector
has its own mechanism for freeing memory (gsl_vector_free
). Is there a way to force the unique pointer to use GSL's vector freeing method? Valgrind (correctly) reports a mismatched use of malloc/delete when creating a unique_ptr<gsl_vector>
below:
#include <memory>
#include <gsl/gsl_vector.h>
void mem_gsl() {
gsl_vector *vec;
vec = gsl_vector_calloc(2);
gsl_vector_set(vec, 0, 2.0);
printf("%f\n", gsl_vector_get(vec, 0));
gsl_vector_free(vec); // Without this, there is a memory leak.
}
void mem_unique_ptr() {
std::unique_ptr<gsl_vector> vec;
vec.reset(gsl_vector_calloc(2));
// Using .get() each time I want to use the gsl_vector seems like overhead.
gsl_vector_set(vec.get(), 0, 2.0);
printf("%f\n", gsl_vector_get(vec.get(), 0));
// Valgrind correctly reports a mismatched use of delete and free.
}
int main(int argc, char *argv[]) {
mem_gsl();
mem_unique_ptr();
return 0;
}
此外,必须调用 get code>每次我想访问一个向量元素似乎相当乏味。
Additionally, having to call get()
each time I want to access a vector element seems rather tedious. Is there a way around this?
推荐答案
你可以通过提供 std :: unique_ptr
使用自定义删除程序。这样的东西可能会:
You can do it by providing std::unique_ptr
with a custom deleter. Something like this would probably do:
auto del = [](gsl_vector* p) { gsl_vector_free(p); };
std::unique_ptr<gsl_vector, decltype(del)> vec(gsl_vector_calloc(2), del);
这篇关于使用unique_ptr和gsl_vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!