正如其他答案指出的,应该避免在c++中使用malloc
(或甚至new
)。无论如何,你的要求:
我需要在这种情况下,而不是new
/delete
使用malloc
逻辑,因为我不得不这样做在cuda ...
在这种情况下,你必须首先为Hessian
实例分配内存,然后遍历它们并为每个Dxx
,Dxy
和Dyy
分配内存。我会为这个像下面创建一个函数:
Hessian* create(size_t length) {
Hessian* obj = (Hessian*)malloc(length * sizeof(Hessian));
for(size_t i = 0; i < length; ++i) {
obj[i].Dxx = (float*)malloc(sizeof(float));
obj[i].Dxy = (float*)malloc(sizeof(float));
obj[i].Dyy = (float*)malloc(sizeof(float));
}
return obj;
}
解除分配你上面create
功能分配的内存,你必须通过Hessian
实例迭代和释放每个Dxx
,Dxy
和Dyy
,然后再解除分配块,存储Hessian
实例:
void destroy(Hessian* obj, size_t length) {
for(size_t i = 0; i < length; ++i) {
free(obj[i].Dxx);
free(obj[i].Dxy);
free(obj[i].Dyy);
}
free(obj);
}
注:使用了该方法将通过避免了内存泄露你的责任。
如果您希望使用std::vector
代替人工分配和释放(这是强烈推荐),可以write a custom allocator它使用cudaMalloc
和cudaFree
喜欢如下:
template<typename T> struct cuda_allocator {
using value_type = T;
cuda_allocator() = default;
template<typename U> cuda_allocator(const cuda_allocator<U>&) {
}
T* allocate(std::size_t count) {
if(count <= max_size()) {
void* raw_ptr = nullptr;
if(cudaMalloc(&raw_ptr, count * sizeof(T)) == cudaSuccess)
return static_cast<T*>(raw_ptr);
}
throw std::bad_alloc();
}
void deallocate(T* raw_ptr, std::size_t) {
cudaFree(raw_ptr);
}
static std::size_t max_size() {
return std::numeric_limits<std::size_t>::max()/sizeof(T);
}
};
template<typename T, typename U>
inline bool operator==(const cuda_allocator<T>&, const cuda_allocator<U>&) {
return true;
}
template<typename T, typename U>
inline bool operator!=(const cuda_allocator<T>& a, const cuda_allocator<U>& b) {
return !(a == b);
}
的使用自定义分配器非常简单,您只需将其指定为第二个模板参数std::vector
:
struct Hessian {
std::vector<float, cuda_allocator<float>> Dxx;
std::vector<float, cuda_allocator<float>> Dxy;
std::vector<float, cuda_allocator<float>> Dyy;
};
/* ... */
std::vector<Hessian, cuda_allocator<Hessian>> hessian;
您通过学习如何使用'std :: vector'来解决问题,并让C++库为您完成工作。有关更多信息,请参阅C++书籍。 –
不要。使这些成员'std :: vector's,然后有这些结构的'std :: vector'。 – NathanOliver
首先从不在C++中使用'malloc'。其次,为什么不使用['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)?或者,甚至可能[[std :: array]](http://en.cppreference.com/w/cpp/container/array)如果大小是固定的,并在编译时已知? –