Question

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.

Was it helpful?

Solution 3

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.

OTHER TIPS

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".

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

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++?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top