Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Strictly speaking, in the C++ object model, malloc allocates storage but doesn't create objects. Accessing that memory as if it contains an object (even a trivial one like int) without properly giving it object lifetime is technically UB. For trivial types, this is rarely enforced in practice, but the standard says to use placement new or std::start_lifetime_as (C++23) to properly begin object lifetime.




> Strictly speaking, in the C++ object model, malloc allocates storage but doesn't create objects.

No - strictly speaking, it does create objects. https://en.cppreference.com/w/cpp/memory/c/malloc.html#:~:te...

It gets confusing (to say the least) if you start questioning the details, but the spec does formally intend the objects to be implicitly created.


I’m not a C++ dev … Does that mean calling constructors? So a default, parameter-less constructor must exist for the given type, and it will be called N times - right?

It's only legal for types that are sufficiently trivial, so the "called constructor" would be trivial. You'll want to follow the links in the page I sent you, it's explained: https://en.cppreference.com/w/cpp/language/classes.html#Impl...



Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: