0

Is it possible in c++ to allocate an object at a specific place in memory? I'm implementing my hobby os kernel memory manager which gives void* addresses to store my stuff and I would like to know how can I use that pointer to allocate my object there. I have tried this:

string* s = (string*)235987532//Whatever address is given.
*s = string("Hello from string\n\0");//My own string class
//This seems to call the strings destructor here even thought I am using methods from s after this in my code...

The only problem with this is that it calls string objects destructor which it shouldn't do. Any help is appreciated.

EDIT: I cannot use placement new because I'm developing in kernel level.

CB Bailey
  • 700,257
  • 99
  • 619
  • 646
The amateur programmer
  • 1,154
  • 2
  • 15
  • 33

4 Answers4

5

Assignment only works if there's a valid object there already. To create an object at an arbitrary memory location, use placement new:

new (s) string("Hello");

Once you've finished with it, you should destroy it with an explicit destructor call

s->~string();

UPDATE: I just noticed that your question stipulates "without placement new". In that case, the answer is "you can't".

Mike Seymour
  • 242,813
  • 27
  • 432
  • 630
4

You need to use placement new. There is not an alternative, because this is precisely what placement new is for.

John Zwinck
  • 223,042
  • 33
  • 293
  • 407
2

I think you should be able to first implement the operator new used by placement new:

void* operator new (std::size_t size, void* ptr) noexcept
{
  return ptr;
}

(See [new.delete.placement] in C++11)

Then, you can use placement new the way it's intended to.

Angew is no longer proud of SO
  • 161,995
  • 14
  • 331
  • 433
0

you can use placement new allocation

void* memory = malloc(sizeof(string));
string* myString = new (memory) string();

source: What is an in-place constructor in C++?

Community
  • 1
  • 1
Creris
  • 1,118
  • 9
  • 19