0

I have tried to come up (just as an experiment, nothing serious) with a macro that wraps alloca in a more object-oriented way, using special "constructor" that returns the size the instance will need together with a pointer to a function that should initialize it.

Writing that using more statements is simple:

void (*initf)(Type *inst);
Type *obj = alloca(Type::init(&initf, ...));
initf(obj);

Obviously, wrapping that in a function would work if it was something else than alloca, but this needs to be inline.

Is it possible to make an expression that performs this kind of task, returning obj as its result? The design doesn't have to stay the same, but generally, there should be a function taking the arguments a constructor should take and produce the size and initializer function. If alloca took as a parameter std::pair<size_t,void(*)(void *ptr)>, it would all be much easier.

I suspect it may not be achieavable in C++, but just for curiosity, could it be done in C? It seems many features intended for macros were added lately.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
IS4
  • 11,945
  • 2
  • 47
  • 86
  • You'd need to make a full-fledged object to handle the RAII needs here; while you could use placement new to initialize the raw memory, if it wasn't wrapped in an object that would guarantee the wrapped object's destructor is manually called when the wrapper goes out of scope, any cleanup would be skipped (C++ has no idea there is anything to clean in the result of an `alloca` call). – ShadowRanger Jan 11 '18 at 01:29
  • And on further consideration, the problem would be that the scope of any such wrapped `alloca` call would not survive the stack teardown when the constructor returns, which probably means you'd need macro magic to avoid creating additional scope. Eew. – ShadowRanger Jan 11 '18 at 01:32
  • @ShadowRanger That's the problem, `alloca` probably *needs* to be called via a macro (I suppose inlining it is not possible) for the memory to be usable. – IS4 Jan 11 '18 at 01:33
  • 2
    And other fun problem: Even if you used macros to wrap such that it looked like object construction (but with `alloca`'s result passed to the real wrapper class underneath), it's [likely broken on many systems](https://linux.die.net/man/3/alloca) (from Bugs section, second paragraph): "On many systems alloca() cannot be used inside the list of arguments of a function call, because the stack space reserved by alloca() would appear on the stack in the middle of the space for the function arguments." – ShadowRanger Jan 11 '18 at 01:36
  • @ShadowRanger Ah, that's unfortunate. But anyway, I wouldn't use this code in a serious project, just as an excercise. – IS4 Jan 11 '18 at 01:49

0 Answers0