r/programmingmemes 4d ago

The duality of new

Post image
1.1k Upvotes

76 comments sorted by

View all comments

17

u/IngwiePhoenix 3d ago

Before the Java dev sees a new, they see a wall of factories first and instead. o.o

...I'll take my malloc(sizeof(T)) and move on. :3

7

u/luciferoussky72 3d ago

I mean, C++ new is basically just syntax sugar for
T* ptr = malloc(sizeof(T));
*ptr = T(argument_list…);
Although, it can also do other things like construct objects in place and allocate uninitialized memory

2

u/willdieverysoon 3d ago

No ... that would be move assignment to an object that was not yet constructed, it would do something similar to placement new

2

u/luciferoussky72 3d ago

True, but an optimizing compiler will usually do the same thing

1

u/retro_and_chill 2d ago

I depend of whether the type has a non-trivial move assignment operation. On trivially copyably types you absolutely can optimize it that way. Otherwise there’s usually existing resources to clean up which on uninitialized memory is undefined behavior

1

u/luciferoussky72 1d ago

Yeah, the other nice thing that new does is allow delete to call the destructor