在 operator new 的重载中调用 new 表达式

Calling the new expression in an overload of operator new

根据 C++ 标准,以下代码是未定义的行为吗?请分享 C++ 标准参考资料。

void* operator new(std::size_t sz)
{
    return ::new int(5);
}

6.7.5.4.11专门讲了对分配函数的要求。它列出了此类函数必须满足的所有要求,并且没有明确禁止调用全局分配函数。

确实是这样说的:

If it is successful, it returns the address of the start of a block of storage whose length in bytes is at least as large as the requested size.

您的函数总是 return 大小等于 sizeof(int) 的块。

6.7.5.4也说这个

If the behavior of an allocation or deallocation function does not satisfy the semantic constraints specified in [basic.stc.dynamic.allocation] and [basic.stc.dynamic.deallocation], the behavior is undefined.

这个答案的前一个版本忽略了这一点。您的函数没有 return 大小等于请求大小(被忽略)的内存块,因此行为未定义。


1this 网站上。