正如其他答案指出的,應該避免在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)如果大小是固定的,並在編譯時已知? –