Placement new

I'm wondering where does placement new's storage gets allocated. Is it the stack or the heap?

1
2
3
4
char buffer[50];
...
int * test = new int [10];
int * test1 = new (buffer) int [10];

And btw, can I just skip to line 4? Or is line 3 required for line 4 to work?
Last edited on
Placement new does not allocate memory, it only calls a constructor on existing memory. That existing memory could be on the stack or the heap - it doesn't matter.
It's actually heap I believe, if you want you can test it by trying to induce stack overflow. If there is a stack overflow error, it is stored on the stack, else it is stored on the heap.
No, placement new does not allocate memory. It uses existing memory (of your responsibility) to construct a new object in.
Last edited on
can I just skip to line 4? Or is line 3 required for line 4 to work?

No, line 4 (the placement new) does not need line 3.

But it does need line 1 (or equivalent), where you've possibly set aside enough memory (on the stack) for the data. As LB pointed out twice, you need to provide the memory required for placement new.

Note that you are providing more memory than needed if your ints are 32 bit (need 40 bytes), but not enough if they are 64 bit (need 80 bytes.)

1
2
3
char buffer[10 * sizeof(int)]; // enough space for 10 ints

int * test1 = new (buffer) int [10];


You could do this instead (where placement new is being used on a dynamically allocated char buffer, which is the same strategy as used by std::vector.):

1
2
3
char * buffer = new char [10 * sizeof(int)];
int * test1 = new (buffer) int [10];
// now have to remember to delete buffer, etc 


Incidentally, as int (in common with all fundamental types) doesn't actually have a constructor (or destructor), this example is a bit pointless. You would just use either int test1[10]; or int * test1 = new int [10]; in practice.

But if you do have cause to use placement new with objects, where there are destructors as well as constructors to worry about, you need to bear in mind that there is no placement delete. So you are responsible for firing off the destructor or equivalent clean-up method. See Stroustrups' FAQ entry for further info.

Bjarne Stroustrup's C++ Style and Technique FAQ
Is there a "placement delete"?
http://www.stroustrup.com/bs_faq2.html#placement-delete

Andy
Last edited on
I'm wondering where does placement new's storage gets allocated. Is it the stack or the heap?

Placement new doesn't allocate any memory ...
It just creates an element (or an array) at the desired location ...
Thanks! It's clearer now.
Topic archived. No new replies allowed.