我们观察一下 placement new 的使用方式和重载方式。使用时就像函数一样有个小括号来表示传参,而接口不考虑第一个固定的 std::size_t,第二个参数开始正好与时候调用时一致。这和我们编写和使用函数非常类似。

是的,为了更加的方便和可拓展,标准也允许自定义接口的参数。
比如我们需要在 new 时传入一个数字和字符串,那么可以像下面这么写:
#include <iostream>
#include <new>
#include <string>
void* operator new(std::size_t sz, std::string str, int num) {
printf("[%d]call:%s %zu\n", __LINE__, __func__, sz);
printf("[%d]params: %s %d\n", __LINE__, str.c_str(), num);
if (sz == 0) {
sz = 1;
}
if (void* ptr = std::malloc(sz)) {
return ptr;
}
throw std::bad_alloc{};
}
int main() {
auto p = new (__func__, __LINE__) int32_t;
}
运行的可能结果为下:
[6]call:operator new 4
[7]params: main 19