Typecasting malloc C++
This question already has an answer here:
when and why is typecasting a call to malloc neccessary in C++?
 Always when not assigning to a void * , since void * doesn't convert implicitly to other pointer types, the way it does in C. But the true answer is you shouldn't ever use malloc in C++ in the first place.  
 I am not suggesting you should use new instead of malloc .  Modern C++ code should use new sparingly, or avoid it altogether if possible.  You should hide all use of new or use non-primitive types (like std::vector mentioned by Xeo).  I'm not really qualified to give advice in this direction due to my limited experience but this article along with searching for "C++ avoid new" should help.  Then you'll want to look into:  
Compile your C library. Compile your C++ library. Make them play nice in whatever "main" program that uses them. Point is if your maintaining a mixed code base, you probably want to isolate the pure C stuff from the C++ stuff. Otherwise your C stuff turns into C++ stuff that only looks like C.
 First, in almost all circumstances just don't use malloc in a C++ program, but prefer new instead because it will make sure that constructors are called when needed, etc.  
 However if for legacy reasons you're trying to avoid as much rewrite as possible - you'll need to cast any malloc call that's not assigned to a void* pointer.  
下一篇: 类型malloc C ++
