On Sep 2, 9:41 am, Kislay <kislaychan...@gmail.comwrote:
Can malloc be used to create/allocate memory to an object of a class .
We use new , but can we use malloc ?
Operator new is required for creating a proper class (not Plain Old
Data). But there are several variations on the new operator.
Read the page referenced in another thread to the C++ FAQ Lite. The
explanation there is thorough and well-written.
More directly:
If all you want is a C-like testing for the NULL pointer because
there's a good reason to avoid throwing std::bad_alloc, new(nothrow)
is a much more reasonable choice than malloc followed by placement
new.
MyClass* tmp = new MyClass; /* throws std::bad_alloc on failure */
MyClass* tmp2 = new(nothrow) MyClass; /* returns NULL on failure;
occasionally useful in normal code */
In my work, I start with new, and defer the decision to use
new(nothrow) until when optimization makes sense. At that time, I
look at how many sources of thrown std::bad_alloc are enveloped by the
try-catch block. If there's only one, there's a good chance of an
object-file size reduction using new(nothrow) rather than new.
Otherwise, the extra code complexity in handling NULL returns
generally isn't worth it.
Using malloc, followed by placement new, is a decidedly low-level
approach that is asking for bugs. About the only thing I'd use
placement new and placement delete for for is implementing STL-like
containers.