问题描述:

This isn't a specific code question, more of a general question regarding some feedback I've been getting. I write C/C++ code quite frequently (which is not to say I'm any good at it, but that's another story), and occasionally I will cast a pointer, e.g.:

void **result = (void **) malloc(size);

I understand that in this particular case, I do not need it, the compiler should take care of it for me. However, whenever someone else looks at my code, I always seem to get rather snide remarks about the fact that I cast these variables. Is there something inherently wrong with using casting?

网友答案:

Answer is different for C and C++. In C you should not cast the return value of malloc.
In C++ you must have to cast it.

网友答案:

The title of your question refers to the general usage of casting. From the example on malloc, it seems that your are asking about c-style casting in c++. in c++, you should avoid using c-style casting. instead of (T) (a) Depending on the case, you should use one of the following 4 types of casting:

static_cast <T> (a)
dynamic_cast <T> (a)
const_cast <T> (a)
reinterpret_cast <T> (a)

Using those c++ type conversions, makes the code safer, and more comprehensive.

A great tutorial can be found in herb sutter's: GotW #17-Casts

And also SO post on C++ casts: When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

网友答案:

Such casts may seem to be useless, but if i'm not wrong, they permit to some compilers to know what to do. Firstable, it resolves warnings if you're compiling with some flags (And i recommend you to do them), and it makes your code portable. Moreover, it proves that you're really understanding what you're doing.

I just wanna add that you're example (with a malloc) should only be used with C code. For c++, it's recommended to use 'new' ;). The casts in C are used like that :

    int        *tab;

    tab = (int *)malloc(theSize * sizeof(*tab));

This is a clean malloc in C ;)

相关阅读:
Top