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