How can I make an object construct itself at a particular location in memory? [duplicate]
Possible Duplicate:
Create new C++ object at specific memory address?
I am writing what is essentially an object pool allocator, which will allocate a single class. I am allocating just enough memory to fit the objects that I need, and I am passing out pointers to spaces inside.
Now my question is this: Once I have gotten a pointer within my pool, how do I construct an object there?
You use placement new. Like so:
new( pointer ) MyClass();
Use placement new.
std::vector<char> memory(sizeof(Myclass));
void* place = &memory[0];
Myclass* f = new(place) Myclass();
Don't use the method defined by the FAQ:
char memory[sizeof(Myclass)]; // No alignment guarantees on this.
As noted in the FAQ it is dangerous as the standard provides no grantees about the alignment of this memory. Using a standard vector does give you guarantees about the alignment because the data section of vector is dynamically allocated and the standard does provide guarantees about the alignment of dynamically allocated memory.
From: n2521 (the copy I have on my desktop) Section: 3.7.3.1
The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type with a fundamental alignment requirement (3.11) and then used to access the object or array in the storage allocated (until the storage is explicitly deallocated by a call to a corresponding deallocation function).
Which points us at 3.11
3.11 Alignment [basic.align]
5 Alignments have an order from weaker to stronger or stricter alignments. Stricter alignments have larger alignment values. An address that satisfies an alignment requirement also satisfies any weaker valid alignment requirement.
Don't forget to manually call the destructor:
f->~Myclass()
Placement new might help.
What uses are there for "placement new"?
Use placement new
char memory[sizeof(Myclass)];
void* place = memory;
Myclass* f = new(place) Myclass();
Remember
You are also solely responsible for destructing the placed object. This is done by explicitly calling the destructor:
f->~Myclass();
EDIT
After reading Martin York's comment and relevant section of the Standard, it is quite certain that you should not use the above method(using objects placed on the stack with placement new). Use std::vector
instead with placement new
as Martin has suggested.
精彩评论