c++ - c++ final 非虚拟类是否被重新解释为可以安全使用的数组?

标签 c++ arrays pointers c++11 reinterpret-cast

我有一个非虚拟最终类,它只声明相同类型的字段。

struct Vector3 final
{
    float X, Y, Z;
    Vector3(float x, float y, float z) : X(x), Y(y), Z(z)
    {

    }

    float Sum()
    {
        return X + Y + Z;
    }
};

将指向此类实例的指针重新解释为 float 组是否安全?

int main(int argc, const char *argv[])
{
    Vector3 v(10, 20, 30);
    Vector3 *pV = &v;
    float *ff = reinterpret_cast<float*>(pV);

    std::cout << ff[0] << std::endl << ff[1] << std::endl << ff[2] << std::endl;

    char c;
    std::cin >> c;

    return 0;
}

最佳答案

不,它不是——数据成员之间可能有填充。

关于c++ - c++ final 非虚拟类是否被重新解释为可以安全使用的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21052836/

相关文章:

c++ - C++ 中哪种递增方法更好?

delphi - 当我直到运行时才知道长度时,如何声明数组?

Javascript 对象多重引用

python - Dlib 人脸检测在 C++ 上表现糟糕,在 Python 上表现不错,为什么?

c++ - 从 ‘std::wstring {aka std::basic_string<wchar_t>}’ 到非标量类型 ‘UString {aka std::basic_string<char>}’ 的转换

c++ - 求和 XOR 的直接公式

c# - 如何使用反射创建 C# 数组并仅输入信息?

c - 当我想添加一些东西作为链表的头部时,为什么我的代码不起作用?

c - 在第二个索引上获取一些垃圾值

c - 通过 void 指针访问各种类型的内存