英文:
What does "*(Vector2*)&x"; in C++ mean?
问题
我正在观看关于C++中联合(unions)的教程,以下是该Youtuber提供的一段代码:
#include <iostream>
struct Vector2
{
float x, y;
};
struct Vector4
{
float x, y, z, w;
Vector2& GetA()
{
return *(Vector2 *)&x;
}
};
void PrintVector2(const Vector2& vector)
{
std::cout << vector.x << ", " << vector.y << std::endl;
}
我特别困惑的是这部分代码:
Vector2& GetA()
{
return *(Vector2 *)&x;
}
这里到底发生了什么?
这是我尝试理解它的方式:
所以我们获取了x
的地址,然后将其分配为Vector2
类型的指针,然后对其进行解引用。为什么我们不只返回&x
呢?我也困惑于如何将x
的地址强制转换为Vector2
类型。
英文:
I'm currently watching this tutorial on unions in C++, and here is a snippet of code provided by the Youtuber:
#include <iostream>
struct Vector2
{
float x, y;
};
struct Vector4
{
float x, y, z, w;
Vector2& GetA()
{
return *(Vector2 *)&x;
}
};
void PrintVector2(const Vector2& vector)
{
std::cout << vector.x << ", ", << vector.y << std::endl;
}
I am particularly confused at this part here:
Vector2& GetA()
{
return *(Vector2 *)&x;
}
What exactly is going on here?
Here is my attempt to try to understand it.
So we are grabbing the address of x
, and then assigning it to be a pointer of Vector2
type, and then dereferencing it. Why do we not just, return &x
? I'm also confused at how you can type coerce the address of x
into a Vector2
type.
答案1
得分: 2
这意味着不多不少,只不过是未定义行为。作者试图告诉编译器“将此Vector4
实例视为Vector2
实例”,但这是错误的做法。
将其拆分成几个部分:
首先,他们获取了this
的第一个成员的地址:
&x
然后,他们进行了C风格的转换,将整个类型系统抛出窗外,告诉编译器“闭嘴,这个指针指向Vector2
”:
(Vector2*) &x
最后,他们对指针进行解引用,现在由编译器视为Vector2
:
* (Vector2*) &x
英文:
It means nothing more, nothing less than Undefined Behaviour. What the author attempted to do is tell compiler "treat this
instance of Vector4
as instance of Vector2
", but that's plain wrong way to do so.
Breaking it down into pieces:
First they get address of the first member of this
&x
Then they do a C-style cast, throwing whole type system out of the window to tell compiler "shut up, this pointer points to Vector2
"
(Vector2*) &x
Finally they dereference the pointer, now treated by compiler as Vector2
:
* (Vector2*) &x
</details>
# 答案2
**得分**: 2
这段代码告诉编译器假装`x`的地址(即`float*`)实际上是`Vector2`类型对象的地址。当然,实际情况并非如此,编译器没有必要采取任何使结果看起来合理的行动。编写这段代码的人假设`Vector2`中的`float x, y`和`Vector4`中的`float x, y, z, w`之间存在某种神秘的联系,使得`Vector4`成员数据的开头看起来像一个`Vector2`对象。然而,在语言定义中并没有要求这样做。
<details>
<summary>英文:</summary>
The code tells the compiler to pretend that the address of `x` (i.e., `float*`) is actually the address of an object of type `Vector2`. Of course, it's not, and the compiler is not required to do anything that makes the result seem sensible. Whoever wrote that assumed that the `float x, y` in `Vector2` and the `float x, y, z, w` in `Vector4` have some mystic connection that will make the beginning of that `Vector4` member data look like a `Vector2` object. There is nothing in the language definition that requires this to work.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论