根据 C++ 标准第 3.7.3/1 段,对象应使用 new 表达式动态创建,C++ 运行时应提供分配函数 ::operator new()
.
偶尔有必要call ::operator new()
directly .
C++ 标准是否允许这样调用 ::operator new()
函数,或者这个(和相关的)函数是否仅供内部使用?
最佳答案
直接调用operator new
和operator delete
是完全可以接受的;它们是全局命名空间的一部分,就像 C++ 版本的 malloc
和 free
与 set_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/