2

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

Anton Stafeyev
  • 761
  • 1
  • 7
  • 20
  • You want to use placement new: `Foo *myClass = new (address) Foo;`: https://en.cppreference.com/w/cpp/language/new – mch Mar 24 '20 at 09:45

1 Answers1

1

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();
Nelfeal
  • 12,593
  • 1
  • 20
  • 39
  • delete myClass will not call a destructor ? – Anton Stafeyev Mar 24 '20 at 09:49
  • If there is no new (not counting *placement new*, which doesn't allocate anything), there should be no delete. However the memory was allocated, it should be deallocated with the corresponding tool. I'm guessing you don't actually need to allocate (nor deallocate) memory in your case. – Nelfeal Mar 24 '20 at 09:50
  • yeah no need to allocate it since it will be just placed there and initialized. and destructor is not needed, but was just curious – Anton Stafeyev Mar 24 '20 at 09:51
  • @AntonStafeyev , I think it is better to keep the destructor. If in future your class creates / holds a resource, the resource would be deallocated automatically. ( Provided you manually write the destructor of the class of course!! ) – Abdus Khazi Mar 24 '20 at 09:56
  • @AbdusKhazi Not sure what you mean. If you are writing modern C++, you likely won't need to write your own destructor. You will need to call it manually, though, unless you don't care and you just exit the program or something. – Nelfeal Mar 24 '20 at 10:05