Reputation: 1308
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.
Upvotes: 0
Views: 520
Reputation: 171127
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.
Upvotes: 2
Reputation: 1128
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++?
Upvotes: 0
Reputation: 254461
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".
Upvotes: 5
Reputation: 249143
You need to use placement new. There is not an alternative, because this is precisely what placement new is for.
Upvotes: 4