gpt4 book ai didi

c++ - 有关将char指针转换为其他类型指针的问题

转载 作者:行者123 更新时间:2023-12-01 14:57:01 29 4
gpt4 key购买 nike

#include <iostream>
struct Test{
int a;
int b;
};
int main(){
char* buffer = (char*)malloc(sizeof(char)*32); //#a
char* ptr = buffer + 4; //#b
new(ptr) Test; //#c
char* ptr2 = buffer + 4; //#d
Test* tptr = reinterpret_cast<Test*>(ptr2); //#e
tptr->a = 1; // #f
}
考虑上面的代码,在 #a处,分配函数 malloc分配存储区域并隐式创建 char[32]类型的数组对象,在以下规则中提到:

Some operations are described as implicitly creating objects within a specified region of storage. For each operation that is specified as implicitly creating objects, that operation implicitly creates and starts the lifetime of zero or more objects of implicit-lifetime types ([basic.types]) in its specified region of storage if doing so would result in the program having defined behavior. If no such set of objects would give the program defined behavior, the behavior of the program is undefined. If multiple such sets of objects would give the program defined behavior, it is unspecified which such set of objects is created.


因此, #b处的代码定义明确,因为可以将指针 buffer视为指向数组的第一个元素,因此它满足 expr.add#4规则。 #c上的代码也定义明确,它将在 ptr指向的存储区构造一个Test类型的对象。 #d#b相同,定义也很明确。
但是,请考虑使用 #e上的代码。现在,指针 ptr2指向 array的第四个元素(由 malloc创建),该元素是char类型的对象,由于其存储已被 Test类型的对象重用,其生命周期已结束。表达式 reinterpret_cast<Test*>(ptr2)static_cast<Test*>(static_cast<void*>(ptr2))等效。

A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If the original pointer value represents the address A of a byte in memory and A does not satisfy the alignment requirement of T, then the resulting pointer value is unspecified. Otherwise, if the original pointer value points to an object a, and there is an object b of type T (ignoring cv-qualification) that is pointer-interconvertible with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.


根据上述规则, Test类型的对象不能与char类型的对象进行指针互转换。因此,我认为结果仍然是指向char类型的对象的指针,该对象是数组的第四个元素,只是其生命周期已经结束。
因此,我想知道 #f上的代码是否由于 tptr没有指向 Test类型的对象而具有未定义的行为?或相反,指针 tptr是否确实指向 Test类型的对象并且代码定义正确?如果我错过其他一些规则,请指出。

最佳答案

Does the code at #f have undefined behaviour due to tptr does not point to an object of type Test?


#a以来,该程序具有未定义的行为,因为 malloc被定义为触发隐式对象创建并返回指向合适的已创建对象的指针,但是能够提供程序其余行为的对象集为空。

关于c++ - 有关将char指针转换为其他类型指针的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63821798/

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