gpt4 book ai didi

c++ -::operator new(size_t) 是否使用 malloc()?

转载 作者:可可西里 更新时间:2023-11-01 15:40:01 24 4
gpt4 key购买 nike

::operator new(size_t) 是在内部调用 malloc(),还是直接使用系统调用/操作系统特定的库调用? C++ 标准怎么说?

this answer它说:

malloc() is guaranteed to return an address aligned for any standard type. ::operator new(n) is only guaranteed to return an address aligned for any standard type no larger than n, and if T isn't a character type then new T[n] is only required to return an address aligned for T.

这表明 new() 不需要调用 malloc()

注意:有一个 SO question关于 operator new 做的所有事情 other 除了分配。

最佳答案

operator new 是如何实现的细节是标准库的特定实现的属性——甚至不是编译器或操作系统。我熟悉一个 (gnu) 并了解其他 3 个——CLang、Apache 和 MSFT。他们都在 operator new 中使用 malloc(),因为它让库开发人员的生活变得如此轻松。

如果不使用 malloc(),表示开发人员将不得不在内存分配方面重新实现很多,并在代码中大量使用依赖于操作系统的逻辑来实际请求内存。当 malloc() 已经存在时,没有人愿意这样做。但绝不是他们必须使用它。

关于c++ -::operator new(size_t) 是否使用 malloc()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34813448/

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