How to create an object design in a specific place in memory?

Possible duplicate:
Create a new C ++ object at a specific memory address?

I am writing what is essentially a allocator of a pool of objects that will allocate one class. I allocate enough memory to match the objects I need, and I pass pointers to spaces inside.

Now my question is this: as soon as I get a pointer inside my pool, how do I build an object?

+3
source share
4 answers

You are using a new placement. For instance:

new( pointer ) MyClass();
+10
source

Use new placement.

std::vector<char> memory(sizeof(Myclass));    
void*             place = &memory[0];          

Myclass* f = new(place) Myclass();

Do not use the method defined in the FAQ:

char     memory[sizeof(Myclass)];  // No alignment guarantees on this.

FAQ, , . , , .

: n2521 ( ) : 3.7.3.1

, (3.11), ( , ).

3.11

3.11 [basic.align]
5 . . , , .

:

f->~Myclass()
+4
+2

char memory[sizeof(Myclass)];    
void* place = memory;          

Myclass* f = new(place) Myclass();   

You are also solely responsible for the destruction of the posted facility. This is done by explicitly calling the destructor:

 f->~Myclass();

EDIT

After reading Martin York’s commentary and the relevant section of the Standard, it’s clear that you should not use the above method (using objects pushed onto the stack with new). Use std::vectorinstead placement new, as Martin suggested.

0
source

Source: https://habr.com/ru/post/1754805/


All Articles