3 ms·
C's malloc and C++ new are pretty different. malloc is a typically C very low level allocator feature, actually it's barely even a whole feature, it's just the
by tialaramex 5y ago
C's malloc and C++ new are pretty different.
malloc is a typically C very low level allocator feature, actually it's barely even a whole feature, it's just the memory allocation step when you're presumably going to want to put something in this expanse of emptiness. Or maybe being C you will forget to do so and then be astonished it's nonsense.
new is a C++ operator that either does the allocation and calls a constructor for one or more objects to fill that newly allocated space or it runs constructors on memory you already got from somewhere else (this use of the same operator is called "placement new" because C++ cannot get enough overloading)
It is very strange to assume allocation in your operators, no other examples beyond C++ come to mind, but most of new's work is running constructors, which don't exist in C.
- torginus 5y agoThe point I was trying to make, that the line is often blurred between language features and standard library calls. C++'s new could've been a function, just like C - it's how std::make_unique works.
- tialaramex 5y agoIt's an operator, and in C++ operators are basically just functions with some syntax sugar because of the extensive overloading. However, C++ doesn't have a single base class, so by making new an operator, it has a default implementation in every type whereas there is nowhere to write a function with that behaviour. This doesn't matter for malloc because C doesn't have a type hierarchy. Edited to add: std::make_unique always makes the thing std::make_unique wants to make, you can't overload that for your new type where it should do something else.