- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
#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 totptr
does not point to an object of typeTest
?
#a
以来,该程序具有未定义的行为,因为
malloc
被定义为触发隐式对象创建并返回指向合适的已创建对象的指针,但是能够提供程序其余行为的对象集为空。
关于c++ - 有关将char指针转换为其他类型指针的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63821798/
我是一名优秀的程序员,十分优秀!