重载算子新功能的限制

Restrictions in overloading operator new function

本文关键字:新功能 重载      更新时间:2023-10-16

运算符新函数可以被重载,但它要求第一个参数是无符号的int,即重载的函数也应该将无符号的int作为其第一个参数。

// Okay since the first argument is unsigned int
void * operator new(size_t size, Arena& arena, std::string msg)
// Not okay. since the first argument is not an unsigned int
void * operator new(Arena& arena, std::string msg)

如何实施? 我们可以对用户定义的函数实施类似的限制吗?

在 C++ 中使用运算符重载时,运算符签名由 C++ 标准确定。该标准更进一步,提到了一些不允许超载的操作者(?:::等(。

我不是一个C++标准中提取东西的语言律师,但正如 cpp-reference 中所述,与任何其他运算符一样,new operator都有公认的预定义函数签名。使用示例中所示的函数签名,似乎定义了用户定义的放置分配函数。根据 cpp-reference,第一个参数应始终是该特定运算符新重载size_t类型。

附言这是operator newoperator new function.