gpt4 book ai didi

c++ - 将指针转换为指针……指向指针?

转载 作者:太空狗 更新时间:2023-10-29 23:43:53 25 4
gpt4 key购买 nike

我找到了这个片段

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 是一个空指针,所以我假设它被转换为一个 Pool 指针并且池被设置为 0。不是他的指针而是池本身,因为第三个 * 在左边。但是 Pool 没有定义 operator=

声明中的

pointer** 显然是指向指针的指针......但在这种情况下这对我来说没有意义,因为 ans 是一个指针.

最佳答案

这里使用 Pool** 的唯一原因是语义正确性,因为大概“隐藏”的 4 字节 header 应该是指向 Pool 的指针(所以 ans 是指向 Pool 的指针,而 *(Pool **)ans 的类型是 Pool *).

除非您能够将 Pool 分配给 NULL,否则您不能执行 *(Pool *)ans = NULL,并且反正这里可能不是预期的效果。像 *(int **)ans = NULL 或更荒谬的 *(Pool ******)ans = NULL 会产生相同的最终效果但如果它最终打算成为指向 Pool 的指针,那么在语义上会很奇怪。

在一天结束时,您将得到:

 +---+---+---+---+- - -
| 0 | 0 | 0 | 0 | ... and nbytes more bytes
+---+---+---+---+- - -

^ ans ^ returned address (ans + 4)

前 4 个字节是指向某个地方的 Pool 的指针。

考虑这个的另一种方法是忽略整个 nbytes 事情,考虑这个一般模式:

void * ptr = malloc(sizeof(TYPE));
*(TYPE *)ptr = VALUE;

这应该是有道理的。现在,如果 TYPE 是一个 Pool * 并且 VALUE 是 NULL 并且您将它放入那个模式,您可以看到它仍然是如何有意义的:

void * ptr = malloc(sizeof(Pool *));
*(Pool **)ptr = NULL;

然后在你的情况下你基本上仍然这样做,虽然你在最后分配了一些额外的字节,但这与这里的类型无关。

顺便说一句,在这里(并且在语义上也是惰性的)硬编码 4 而不是 sizeof(Pool *) 可能会带来麻烦。

关于c++ - 将指针转换为指针……指向指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39431325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com