void* operator new(size_t nbytes)
{
if (nbytes == 0)
nbytes = 1; // so all alloc's get a distinct address
void* ans = malloc(nbytes + 4); // overallocate by 4 bytes
*(Pool**)ans = NULL; // use NULL in the global new
return (char*)ans + 4; // don't let users see the Pool*
}
这里是https://isocpp.org/wiki/faq/dtors
我花了一个多小时试图理解*(Pool**)ans = NULL;
的含义。
ans
是一个void指针,所以我会认为它被转换为Pool
指针并将池设置为0。不是指针而是池本身,因为左边有第三个*
。但是,Pool没有定义operator=
。
在声明中的pointer**
显然是指向指针的指针......但在这种情况下,对我来说这毫无意义,因为ans
是单个指针。
4
可能最好重写为sizeof(Pool *)
。或者完全删除它 - 偏移量更像是一种肮脏的技巧(程序员试图添加伪安全措施),并且在实际使用中没有太大作用。(如果删除它,请同时修改其他直接操作Pool
的函数,因为它们也将使用该偏移量)。 - Peter