将指针转换为指针.指针
casting pointer to pointer... to pointer?
我找到了这个片段
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字节头应该是指向Pool
的指针(因此ans
是指向Pool
的指针,而*(Pool **)ans
的类型是Pool *
)。
你不能做*(Pool *)ans = NULL
,除非你能够将Pool
分配给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 *)
可能会带来麻烦(并且在语义上也是懒惰的)。
不,它不是"转换为池指针"。强制类型是:
(Pool**)
这不是指向Pool
的指针。这是一个指向Pool
的指针。
那么,现在让我们假设ans
是Pool **
,因为它就是这样。在这种情况下:
*ans = NULL;
这将把ans
指向的指针设置为NULL
。而不是Pool
类的制造实例。而是指向它的指针
但是这里有一个更大的问题:
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*
这是非常旧的代码,它只在指针长度为4字节时才有效。
在现代64位平台上,使用8字节长的指针,这整个事情将惨败…
- 正在将指针转换为范围
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- C++:Lambda 函数指针转换的用例是什么?
- 如何将 int 指针转换为浮点指针
- 为什么在将 void 指针转换为整数指针时出现分段错误
- 将(N 个字节)无符号字符指针转换为浮点数和双 C++
- 我们可以在不知道其真实类型的情况下将基类指针转换为派生类指针吗?
- C++中数组大小未知的指针转换
- Antlr cpp 运行时 任何错误的指针转换?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- C 指针转换会导致内存访问冲突
- 模板类实例化中的指针转换无效
- 函数调用歧义(用户定义的转换和 Derived2Base 指针转换)
- 如何将 void(*)() 类型的指针转换为 void*
- 数组到指针转换期间的临时具体化
- 直接为浮点变量分配十六进制整数与通过指针转换分配之间的区别
- 将基类指针转换为派生的类指针
- 应对 std::字符串中的 std::<char>指针转换后的向量
- 在编译时将函数指针转换为 std::uintptr_t
- 将基类指针转换为未知派生类指针