【问题标题】:What is the meaning of the below sentence in c++ [duplicate]c ++中以下句子的含义是什么[重复]
【发布时间】:2012-04-19 11:08:17
【问题描述】:

可能重复:
C++'s “placement new”

在下面的代码中第3行代表什么,是类型转换的方式吗?或者什么

 void someCode()
 {
   char memory[sizeof(Fred)];     // Line #1
   void* place = memory;          // Line #2

   Fred* f = new(place) Fred();   // Line #3
   // The pointers f and place will be equal

   ...
 }

【问题讨论】:

  • 由于对齐要求,这不起作用。 Fred 类型可能需要比 char 更严格的对齐方式。您应该改用 aligned_storage,在 C++11 和 TR1 中可用。

标签: c++ new-operator placement-new


【解决方案1】:

这是Placement new的典型用法。
它允许您分配内存,然后在该特定内存位置构造对象。

第 3 行本质上只是调用构造函数 Fred::Fred()Fred 构造函数中的this 指针将等于place。因此,返回的指针 f 将等于 place

【讨论】:

  • 嗨,Als,感谢您的回复...这个指针(即指向 Fred 的指针)怎么会等于 void*?,
  • @LLL:这就是placement new的实现为你做的事情。它将place的地址分配给f。这是新展示位置提供的功能。
  • 谢谢澄清..这是我想要的..
猜你喜欢
  • 2013-12-31
  • 1970-01-01
  • 2015-07-14
  • 2014-05-19
  • 2022-01-14
  • 2013-04-26
  • 2014-03-22
  • 1970-01-01
  • 2019-09-25
相关资源
最近更新 更多