c++ - 是否允许 C++ 代码直接调用 `::operator new()`?

标签 c++ memory memory-management

根据 C++ 标准第 3.7.3/1 段,对象应使用 new 表达式动态创建,C++ 运行时应提供分配函数 ::operator new() .

偶尔有必要call ::operator new() directly .

C++ 标准是否允许这样调用 ::operator new() 函数,或者这个(和相关的)函数是否仅供内部使用?

最佳答案

直接调用operator newoperator delete是完全可以接受的;它们是全局命名空间的一部分,就像 C++ 版本的 mallocfreeset_new_handler 交互bad_alloc 异常更好一些。 C++ ISO 标准甚至包含一些这样的示例。例如,§13.5/4 有这个例子:

Operator functions are usually not called directly; instead they are invoked to evaluate the operators they implement (13.5.1 - 13.5.7). They can be explicitly called, however, using the operator-function-id as the name of the function in the function call syntax (5.2.2). [Example:

complex z = a.operator+(b); // complex z = a+b;

void* p = operator new(sizeof(int)*n);

—end example]

关于c++ - 是否允许 C++ 代码直接调用 `::operator new()`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5063924/

相关文章:

go - 为什么Go经常将字符串数据存储在未对齐的地址处

Delphi - 如何释放属于 2 个(或更多)列表的对象

C++ 结构内存布局和 OpenGL glVertexPointer?

C++ Windows Phone 8 组件

c++ - 为什么在类声明中使用宏

c++ - 性能权衡 - MATLAB 何时比 C/C++ 更好/更慢

java - 在内存中执行 jar/class 文件

c - C 中的越界地址/指针

c++ - 如何从 QtQuickWidget 加载 qt Quick ui 表单?

javascript - Node.js 中 process.nextTick 的正确用例是什么?