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?
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.
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.
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With