camino
camino

Reputation: 10584

Do we still need "placement new" and "operator new"?

It seems that allocator does the same work as “placement new” and “operator new”. and its interface is more convenient.

For example:

string *ps = static_cast<string *>(operator new(sizeof(string)));
new (ps) string("Hello");
cout<<*ps<<endl;

can be rewritten to

allocator<string> as;
string *ps2 = as.allocate(1);
as.construct(ps2,"Hello");
cout<<*ps2<<endl;

So it that means that "placement new" and "operator new" are obsolete?

Upvotes: 9

Views: 313

Answers (1)

CouchDeveloper
CouchDeveloper

Reputation: 19106

They are still needed. How else would you implement your custom allocator? ;)

Edit:

This answer deserves more explanation:

If you take a look at the std::allocator's construct member function you can see that it uses the placement new operator.

So, the responsibility of an allocator is to allocate uninitialized storage big enough for the object via member function allocate, and then "in-place" construct it into this storage via its construct member. The latter is performed using placement new.

Upvotes: 5

Related Questions