首页 > 解决方案 > Placement-new vs new-expression

问题描述

Again with placement new I've found an example on this forum like this:

char *buf  = new char[sizeof(string)]; // pre-allocated buffer
string *p = new (buf) string("hi");    // placement new
string *q = new string("hi");          // ordinary heap allocation

Here is the link to the original answer:

What uses are there for "placement new"?

标签: c++new-operatorplacement-newnew-expression

解决方案


为什么用户没有在数组分配上调用 operator new 而不是使用 new 表达式?:

我们无法回答这个问题,因为我们不是那个用户。您应该向用户询问 - 尽管该示例是在 1998 年编写的,但与他们联系可能并不容易。我的猜测:他们不知道非放置运算符 new 存在,或者他们不知道它的用途。在这种情况下,重用 char 数组的内存是一种直观的选择。

请注意,首先创建单个动态std::string对象的示例毫无意义(我假设string示例中就是这样)。

我有一个类似的问题给你:你为什么operator new[]在你的建议中使用而不是operator new?更重要的是,为什么不使用分配器呢?

我的猜测正确吗?

  1. 正确的。
  2. 正确的。
  3. 这是一个问题,而不是猜测。我在上面介绍过。
  4. 它会失败。但这无关紧要,因为char它是默认可构造的。

推荐阅读