Just as it's possible to create a new instance of an object in the heap using new Class()
, is it possible to create an object in the stack?
Sure, simply declare it, without static
, as a local variable inside of a function, eg:
void doSomething()
{
...
MyObject myObject; // <-- allocated on the stack
...
}
suppose that I have this:
static int emptyArray[100000];
there's sufficient RAM space, not allocated by the OS, for me to build my object. Can I use a custom allocator and build my object in a subset of this array?
You don't need a custom allocator, you can use placement-new
for that, eg:
static int emptyArray[100000];
...
MyObject *myObject = new (&emptyArray[offset]) MyObject; // <-- allocated inside of emptyArray
...
myObject->~MyObject(); // <-- must call destructor manually
Just make sure that offset
is an even multiple of MyObject
's size and alignment. You can use std::aligned_storage
to help you with that, eg:
#include <type_traits>
static const int MaxObjects = ...;
static std::aligned_storage<sizeof(MyObject), alignof(MyObject)>::type emptyArray[MaxObjects];
...
MyObject *myObject = new (&emptyArray[index]) MyObject;
...
myObject->~MyObject();