是否将“指向结构体的指针的地址”转换为“第一个成员是指向结构体的指针的结构体的地址”UB?

问题描述 投票:0回答:1
  1. 我有一个名为
    Node
    的结构,其第一个成员是
    Node* p_next
  2. 我有一个指向第一个节点的指针,称为
    p_head
  3. 我想将
    &p_head
    类型的
    Node**
    转换为
    Node*
    ,并将其存储在
    p_node_before_head
    中。这样我就可以将
    *p_node_before_head
    视为一个节点,其中
    p_node_before_head->p_next
    的值就是
    p_head
  4. 的值
#include <iostream>

struct Node{
    Node* p_next;
    int item;   
};

int main(){
    Node head = {nullptr, 5};
    Node* p_head = &head;
    
    //By pretending that "p_head" is a node whose first element is a pointer to the head,
    //we create a new pointer that points to this "node before the head"
    Node* p_node_before_head = reinterpret_cast<Node*>(&p_head);
    
    Node* p_head2 = p_node_before_head->p_next;
    std::cout << p_head2->item << std::endl;
}

这是重新解释强制转换未定义的行为吗? 我对如何确定是否将一种类型的指针强制转换为另一种类型的指针感到有点困惑

pointer-interconvertibility

c++ undefined-behavior reinterpret-cast pointer-conversion
1个回答
0
投票

不,这是未定义的行为。您永远不能假装某种类型的对象存在于您从未显式(或隐式)创建此类类型的对象的某个内存位置。

在地址

&p_head
处有一个
Node*
对象,但没有
Node
对象。因此
reinterpret_cast
的结果不能指向任何
Node
对象,因此成员访问
p_node_before_head->p_next
具有未定义的行为。

指针可互换性甚至不重要,因为首先在相关地址处没有相关的

Node
对象。所以肯定不存在任何可以与
Node*
对象进行指针互换的对象。

© www.soinside.com 2019 - 2024. All rights reserved.