I am new to placement new so I wanted to separate allocation from initialization using it along operator new to allocate and construct an array of my user-defined type class Foo.
here is what I've tried:
struct Foo{
Foo(int x) : x_(x){
std::cout << "Foo(int)\n";
}
~Foo(){
std::cout << "~Foo()\n";
}
int x_ = 0;
};
int main(){
Foo* pf = static_cast<Foo*>(operator new[](10 * sizeof(Foo) ) );
for(int i = 0; i != 10; ++i)
new(pf + i)Foo(i * 7);
for(int i = 0; i != 10; ++i)
std::cout << pf[i].x_ << ", ";
std::cout << '\n';
for(int i = 0; i != 10; ++i)
pf[i].~Foo();
operator delete[](pf);
}
- The code looks to work fine so please guide me if I've missed something. And is this similar to how
class allocatorworks? (separate allocation from initialization).