Please note this question is not about malloc
in C or malloc
vs new
/smart pointers in C++.
If I use malloc
in C++, what kind of cast should I use? The following all work.
int *a = (int *)malloc(sizeof (int));
int *b = static_cast<int *>(malloc(sizeof (int)));
int *c = reinterpret_cast<int *>(malloc(sizeof (int)));
Live example: http://ideone.com/lzfxcm
I prefer to use C++ style casts in my code as much as possible and I want to adopt safe coding habits. Please advise with this in mind.
Thank you.
Since malloc
returns a pointer to void
, there is no reason to use a C++ - style cast on the pointer: you get a chunk of raw memory, with no structure behind it, so the only thing your can tell the compiler by adding a cast is that you plan to use this memory for data of a particular kind. Compiler must agree with you on that, because it has no additional information to double-check your decision. Neither static_cast<T>
nor the reinterpret_cast<T>
offer a particular advantage over the C-style cast, and the C-style cast is shorter.
From the personal perspective, I looked at a lot of C++ code, but I've never seen a C++ - style cast used with malloc
, only the C-style.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With