c++ - Placement new using void* bits as storage -


assuming sizeof(t) <= sizeof(void*), following defined / portable? ...

void* storage = 0; new (&storage) t(t); 

this seems used sensible small-object optimisation, if so.

you passing valid address, , if memory pointed big enough contain object, , alignment compatible object, it's fine code.

the alignment should implicitly correct if sizeof(t) <= sizeof(storage). can paranoid , explicitly set with:

alignas(t) void* storage = 0; 

although think manually setting alignment isn't needed, , sizeof(t) <= sizeof(storage) mean correct alignment guaranteed, i'm not 100% sure.

note because type of storage void* doesn't mean anything. particular placement new defined standard as:

void* operator new(std::size_t count, void* ptr); 

the address parameter void*, meaning type pointed can anything. requirement it's address valid memory.

however, if storage ever goes out of scope, you're busted if object contained within needs destructed. need call destructor before storage goes out of scope.

also note "placement delete" (this automatically called if needed, it's not possible write code it) never free memory. storage being on stack still fine if placement delete gets called (like when constructor throws.)


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -