Yves
Yves

Reputation: 12371

c++ allocator: operator new or placement new

After reading this link, I've known that placement new was too hard to use properly. Then I found std::allocator, so I thought std::allocator should have used placement new because it could separate allocation and do construction in two steps.

However, it seems that How are allocator in C++ implemented? tells me that std::allocator is implemented by operator new, instead of placement new. I'm confused now. If it doesn't use placement new, how could it separate allocation and do construction in two steps?

Upvotes: 0

Views: 987

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

You have to differ between the operator new function and new expressions.

The former (the operator new function) only allocates memory. The latter (new expression) calls operator new to allocate memory and then invokes the constructor.


std::allocator have two functions to implement allocation and construction: allocate and construct.

The allocate function uses the operator new function to allocate memory. The construct function uses placement-new to construct objects. Which seems to be the two-step process you want.

Upvotes: 3

Related Questions