Hacker News new | ask | show | jobs
by ReleaseCandidat 1648 days ago
> It is not, they diverged since decades now.

AFAIK you always had to cast `void *` in C++ (like the return value of `malloc`).

1 comments

Why on Earth would one use malloc in C++? Instead of using ’new’ if explicit allocation is desired.
If you need to change the buffer size afterwards.

My understanding is that most implementations of new call malloc under the hood (this may or may not be outdated at this point, I haven't kept up with C++ implementation) and both of these systems introduce a layer of record keeping, so if you're in an extremely memory constrained environment, you may want to use malloc directly.

If you want your code to be noexcept, you need to call malloc and handle the case where it returns null as new can throw (this is UB in theory, but in practice I'm pretty sure everything just aborts) to strip out all the stack-unwinding code.

If you want to avoid the constructor call (for whatever reason).

We are talking about the question if C is a subset of C++. `new` certainly isn't a part of C, so also not an element of the intersection of C and C++.

Idiomatic C code doesn't explicitly cast the return value of malloc

    foo *bar = malloc(sizeof *bar);
C++ did AFAIK never (certainly not with C++98, the question is if it had been allowed sometime before the standardization, but I think it never did) allow this, so you always had to do

    foo *bar = (foo *)malloc(sizeof *bar);
Therefore, C is not a subset of C++. But a (non-empty ;) intersection of C and C++ exists.
> Why on Earth would one use malloc in C++? Instead of using ’new’ if explicit allocation is desired.

That was the point of my original comment that C++ and C are not the same language :)