0
struct entity {
    int x;
};
.........
void* memory = GetMemoryFromMyCustomAllocator();
entity* Entity = (entity*) memory;
Entity->x = 1;

I want to avoid new, delete or placement new. I use c++ because I need the OOP features.

Is the above a valid way to do so? Instead of having a constructor I would just write a function InitializeEntity , same for destructor. Are there any downsides? Thank you.

Gavriil
  • 47
  • 1
  • 2
  • 7
  • 2
    You say that you're "using C++ because you need the OOP features." So, why are you using "straight-C" techniques here? That's what objects, with their constructor and destructor routines, are *for.* And this is also what "container classes" are for ... so that you aren't allocating contiguous chunks of memory and referencing them with pointers! – Mike Robinson Jan 31 '20 at 19:27
  • 1
    Why avoid placement new? It’s built pretty much exactly for your use-case: all it basically does is call constructors. Then you can call your destructor manually with `Entity->~entity();` before freeing the memory via your custom deallocator. – nneonneo Jan 31 '20 at 19:28
  • That's more to OOP than just ctors. Inheritance or polymorphism is trickier in C. – Gavriil Jan 31 '20 at 19:29
  • @nneonneo What if I dont have a destructor? – Gavriil Jan 31 '20 at 19:33
  • The downside is that the code is Undefined Behavior; there is no `entity` object at the location where the pointer points to. Placement-new is a way to create objects at a certain memory location. – rustyx Jan 31 '20 at 19:34
  • @Gavriil then calling the destructor will just call the default destructor, which will clean up the fields. It would be a no-op if you don’t have any non-trivial destructors in the fields. Plus you said you’d be writing custom InitializeEntity and presumably some kind of FinalizeEntity anyway; with placement new you just hook into C++‘s existing mechanisms instead of rolling your own. – nneonneo Jan 31 '20 at 19:37
  • @rustyx What it means there is no object `entity` at the location? I would argue that it is. Does new adds some sort of etiquette to the allocated chunk? – Gavriil Jan 31 '20 at 19:40
  • @kmdreko Yes thank you! So this is an actual difference between C and C++, the above code would be valid in C :) – Gavriil Jan 31 '20 at 19:54

1 Answers1

1

Is the above a valid way to do so?

No. Not in C++.

In order to create a dynamic object, you must use a new-expression (or a function that calls a new-expression).

Are there any downsides?

Downside is that the behaviour of the program is undefined. Upside is that you had a few characters less to type by skipping placement new.

There is a proposal P0593rX that proposes introducing C-style implicit creation of (trivial) objects into C++.

eerorika
  • 232,697
  • 12
  • 197
  • 326