指针如何引用不同的类型
How can a pointer refer to a different type?
(4.1/1( 如果左值所指的对象不是 类型 T 并且不是派生自 T 类型的对象,或者如果该对象 未初始化,需要此转换的程序具有 未定义的行为。
由此,我假设
struct B {
int x; };
B *p;
*p; //undefined behavior
*p
是一个左值,指的是未初始化的对象。它如何引用不是"B"类型或其派生类型的对象?我是不是误会了什么?
简单:
int n = 5;
double * p = reinterpret_cast<double*>(&n);
*p += 1.0; // undefined behaviour: p points to an int, not a double
++*reinterpret_cast<int*>(p); // legal; pointer can be cast back-and-forth
不太容易:
union bogus { int * a; double * b; } B;
int n;
B.a = &n;
*B.b += 1.0; // undefined behaviour
常见的 C 陷阱(不产生诊断!
void do_a(void * p) { ++*reinterpret_cast<int*>(p); }
void do_b(void * p) { *reinterpret_cast<double*>(p) += 1.0; }
int main() { int n = 4; do_b(&n); /* eek */ }
简单。
int i;
B *p;
p = (B*)&i;
做。
使它指向不属于对象 T 或派生类型的内容的一种方法是使用指针强制转换键入双关语:
struct A{ int x; };
struct B{ float x; };
A x;
B *p = (B*)&x;
*p; // Undefined behavior
在此示例中,指针p
未指向类型 B
的内容。它指向不兼容的 A
类内容。
请注意,此示例还违反了严格别名 - 这也是未定义的行为。
相关文章:
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 将成员函数的返回类型引用到C++中的自定义类
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- C++:类类型引用运算符=用法
- 将 const 类型引用对象注册为类成员对象C++
- 错误:绑定到类型引用会丢弃限定符
- 如果作为基类型引用传递,派生类型会解构吗
- 未分配返回未定义对象类型引用的 C++ 函数的返回值时会发生什么情况
- 类型引用的初始化无效
- C++ 从函数返回多个类型引用并将它们强制转换为我们需要的类型
- 函数常量返回类型:类型引用的初始化无效
- 将类型的嵌套类型引用为类模板的参数的问题
- 与返回类型(引用、常量引用)混淆
- 调用具有const键类型引用的std::指针集的count方法
- 返回运算符类型=-引用或值
- 非类型引用形参/实参
- c++中定义不同类型引用的区别
- 为什么返回类型引用输出流
- 非类型(引用)模板参数和链接
- 类型引用的初始化无效