gpt4 book ai didi

c++ - operator new(n) 与 new unsigned char[n] 用于放置 new

转载 作者:可可西里 更新时间:2023-11-01 17:37:08 29 4
gpt4 key购买 nike

我正在分配内存,稍后将用于构造具有放置 new 的对象。我应该使用 operator new(n),还是应该使用 new unsigned char[n]?为什么?

最佳答案

因素:

  • new[] 必须与 delete[]/new()delete 匹配
  • 他们交流不同的东西。 operator new(n) 是出于未指定目的的内存请求,而 new unsigned char[n] 松散地暗示有意将字符存储在那里。

数组形式可能稍微性能/效率较差 - 具体细节取决于您的实现:

5.3.4/12 new T[5] results in a call of operator new where x is a non-neagtive unspecified value representing array allocation overhead: the result of the new-expression will be offset by this amount from the value returned by operator new[]....

顺便说一句——两者都没有被初始化:

  • operator new()void* 返回到未初始化的内存:请参阅 3.7.4.1/2 “从返回时分配存储的内容没有限制分配函数”,而 5.3.4/15 说“创建 T 类型对象的新表达式按如下方式初始化该对象:如果省略了新初始化程序,则该对象被默认初始化 (8.5)”; 8.5/6 表示只有类类型的默认构造函数提供初始化。

关于c++ - operator new(n) 与 new unsigned char[n] 用于放置 new,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16518894/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com