如何使用malloc()将C语句转换为C ++? [英] How to convert a C statement using malloc() to C++?
问题描述
我的C代码中有一个缓冲区
I have a buffer in C with this code
buffer = malloc(sizeof(uint32_t)*CACHE_LEN*2);
如何将这一行更改为C ++?
How can I change this line to C++?
使用malloc
或new[]
更好吗?
我不明白这个sizeof(uint32_t)
的含义.
Is it better with malloc
or with new[]
?
I cannot understand the meaning of this sizeof(uint32_t)
.
推荐答案
您提到的行将在C ++中很好地编译,除了以下事实:如果buffer
不是void *
,则可能需要强制转换在C ++中返回malloc
的值,您不需要在C中执行(也许不应该这样做).
The line you mention will compile fine in C++, save for that fact that if buffer
is not a void *
, then you may need to cast the return value of malloc
in C++, which you don't need to do in C (and probably should not do).
EG:
uint32_t *buffer = (uint32_t *) malloc(sizeof(uint32_t)*CACHE_LEN*2);
但是,您可能希望转换为new
/delete
范例;这不仅需要更改该行.
However, you may wish to convert to a new
/ delete
paradigm; that will require more than just changing that line.
EG:
uint32_t *buffer = new uint32_t[CACHE_LEN*2];
...
delete[] buffer;
如果您仍然想更像C ++,请使用std::vector
或类似的方法:
If you want to be more C++-like still, then use std::vector
or similar:
std::vector<uint32_t> buffer(CACHE_LEN*2);
这篇关于如何使用malloc()将C语句转换为C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!