C++ Constructor without new

Viewed 78

I am trying to utilize c++ in embeded application. and i ran into a theoretical problem

Given that i have no dynamic allocation i dont use "new" operator. The question is regarding calling constructor for object and destructor.

I would like to put my object at x address in memory. i declare it like that:

Foo *myClass = (Foo *) 0x1; //for example
//I guess i need to call constructor manually ?
myClass->myClass();

So what would be a solution to call the constructor other then manually invoke it. Should i just make a new operator my self ? for example

void * operator new(size_t size, uint32_t address)
{
  return (void *)(address); 
}

compiler used arm-none-eabi-g++, target armv7-m

1 Answers

Assuming the memory at address 0x1 is allocated, you can use placement new:

Foo *myClass = new(0x1) Foo;

To destruct your object, you can call the destructor manually:

myClass->~Foo();
Related