Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 476
camino Avatar asked Jul 26 '13 18:07

camino


People also ask

In which cases we would need to use placement new?

Use cases. Placement new is used when you do not want operator new to allocate memory (you have pre-allocated it and you want to place the object there), but you do want the object to be constructed.

What is placement new and why would I use it?

Placement new is a variation new operator in C++. Normal new operator does two things : (1) Allocates memory (2) Constructs an object in allocated memory. Placement new allows us to separate above two things. In placement new, we can pass a preallocated memory and construct an object in the passed memory.

What is the difference between operator new and the new operator?

new vs operator new in C++ When you create a new object, memory is allocated using operator new function and then the constructor is invoked to initialize the memory. Here, The new operator does both the allocation and the initialization, where as the operator new only does the allocation.

Which is true about new operator?

Which among the following is true? Explanation: The new operator can't allocate functions but can allocate pointer to the functions. This is a security feature as well as to reduce the ambiguity in code. The new keyword is not given functionality to directly allocate any function.


1 Answers

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.

like image 71
CouchDeveloper Avatar answered Sep 24 '22 18:09

CouchDeveloper