我们平时使用使用的new operator会使用placement new在内存中创建对象吗?
placement new的作用就是在operator new分配好的内存上执行对象的构造,那么new operator使用了operator new来申请内存之后是使用了placement new吗?如果没有话是怎么构造的呢?和placement new有关系吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
new
is not anoperator
!In c++,
new
andoperator
are both keywords.new int(x)
is a(n) (new-)expression. operator new is a function. new operator in your title is new-expression indeed. new-expression will invoke oeprator new function.In a nutshell, placement new will use already allocated memory to construct the object. Where is the already allocated memory from? Either from new expression(free store) or allocated from
activation record
likeint buffer[10]
, both ok.Above is my answer to your questions
BTW, from the case
int buffer[10]
, we can see pre-new-expression is not a must for placement new(however, note that placement new itself is a new-expression, which will invoke operator new function because all it does is just construct here). If your question is "will placement new always be after operator new/new-expression", it will be a good question.Update
One year ago, I was confused about how to combine operator new with the constructor then asked a question, FrankHB answered my question: https://tieba.baidu.com/p/508... Now, look back to this question, it is a X-Y question, what really confused me was how does new expression invoke constructor, so it is not related to placement new. Hope it will also inspire you.
Update again
new expression does two things:
You and I(one year ago) are both confused about how does compiler initialize the object(via constructor or else) after allocating. Yes, I mentioned compiler, because C++ standard guarantee new will do the two things, but didn't how to, so, its compiler's work. So, it is not c++'s work, just compiler's. Now, we can see the assembly:
-O0:
codes related the new expression is follows: a
Now, it is clear enough, right? assemble calls two procedures, oeprator new and Foo::Foo(int)
That's all, cheers!
So, your question is how the two combined?
没有,普通的new不通过placement new,new和placement new都通过构造函数来初始化对象。