简体   繁体   English

C ++:如何获取浮点指针的地址并将其转换为void **

[英]C++: How to get the address of a float pointer and convert it to void**

In C++ programming, I often need to acquire the address of a pointer and convert it to void ** . 在C ++编程中,我经常需要获取一个指针的地址并将其转换为void ** For example, typically when using CUDA: 例如,通常在使用CUDA时:

int main() {
    float *data;
    size_t size = sizeof(float) * 1024;

    CUDA_CHECK(cudaMalloc((void **)&data, size));   // question about this line
    ...
    CUDA_CHECK(cudaFree(static_cast<void *>(data)));

    return 0;
}

My problem is that the cast of a float ** to void ** using C-style type cast irks me, as I don't want to use that in C++ programming. 我的问题是使用C样式类型强制转换将float **void **会让我感到不舒服,因为我不想在C ++编程中使用它。

So far, I've been using reinterpret_cast<void **>(&data) instead, but I'm not happy with it. 到目前为止,我一直在使用reinterpret_cast<void **>(&data) ,但我对此并不满意。 For some reason I don't think this is the proper way to do it. 由于某些原因,我认为这不是正确的方法。

I tried doing &static_cast<void *>(data) once very stupidly, as this obviously fails for trying to get the address from a rvalue. 我曾经非常愚蠢地尝试过一次&static_cast<void *>(data) ,因为这样做显然无法尝试从右值获取地址。

I've done some search on Google and Stack Overflow, but I'm having a hard time finding good keywords for the query. 我已经在Google和Stack Overflow上进行了一些搜索,但是很难为查询找到合适的关键字。

I've also been learning the concept of rvalue reference, but I don't think it was designed for this problem. 我也一直在学习右值引用的概念,但我认为它不是针对此问题而设计的。

So my question is, what is the proper C++ way to cast from float ** to void ** in this context? 所以我的问题是,在这种情况下,从float **void **的正确C ++方法是什么? Also, is there a way to static_cast to void * and still get the address from the returned value, like rvalue reference? 另外,有没有办法让static_cast变为void *并且仍然从返回值中获取地址,例如右值引用? (PS: I still don't quite understand rvalue reference, so forgive me if this is a rookie mistake) (PS:我仍然不太了解右值引用,因此如果这是菜鸟错误,请原谅我)

Edit -------------- 编辑 --------------

Sorry I didn't make myself clear. 对不起,我没有说清楚。 I don't want to declare a void * here. 我不想在这里声明一个void * I just want to somehow doing a 'proper' C++ cast to get this done, preferably in just one line. 我只是想以某种方式执行“适当的” C ++强制转换才能完成此操作,最好仅一行完成。

More Edit ---------- 更多编辑 ----------

I do understand that using a void * the proper way, as @MM pointed out below (in fact, that's precisely what I've been doing for some time now). 我确实理解使用void *的正确方法,如@MM在下面指出的(实际上,这正是我现在已经做的一段时间了)。 I'm just curious if there is any proper way that avoids using void * . 我只是好奇是否有任何避免使用void *适当方法。

I'd do it this way: 我会这样:

void *newdata;
CUDA_CHECK(cudaMalloc(&newdata, size));
float *data = static_cast<float *>(newdata);

CUDA_CHECK(cudaFree(data)); // or pass newdata, doesn't matter

And obviously I'd wrap those chunks up into a smart pointer with RAII. 很显然,我会使用RAII将这些块包装成一个智能指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM