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.

8
  • 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! Commented Jan 31, 2020 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. Commented Jan 31, 2020 at 19:28
  • That's more to OOP than just ctors. Inheritance or polymorphism is trickier in C. Commented Jan 31, 2020 at 19:29
  • @nneonneo What if I dont have a destructor? Commented Jan 31, 2020 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. Commented Jan 31, 2020 at 19:34

1 Answer 1

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++.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you please give me an example that breaks the above code?
@Gavriil It is already broken. Behaviour of the program is undefined.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.