Inquiry about class variable declarations in C++

前端 未结 6 1176
悲&欢浪女
悲&欢浪女 2021-01-19 00:43

I have a class to represent a 3D vector of floats:

class Vector3D
{
    public:

    float x, y, z;
    float * const data;

    Vector3D() : x(0.0), y(0.0),         


        
6条回答
  •  面向向阳花
    2021-01-19 01:33

    No, this is undefined behaviour, for two reasons:

    • Firstly for the padding issues that everyone else has mentioned.
    • Secondly, even if things are padded correctly, it is not valid to dereference a pointer with an offset that would take it beyond the bounds of what it's pointing to. The compiler is free to assume this, and make optimisations that would lead to undefined behaviour if you violate it.

    However, the following would be valid:

    class Vector3D
    {
    public:
        std::array data;
        float &x, &y, &z;
    
        Vector3D() : data(), x(data[0]), y(data[1]), z(data[2]) { }
        Vector3D& operator =(Vector3D const& rhs) { data = rhs.data; return *this; }
    };
    

    std::array is new to C++0x, and is basically equivalent to boost::array. If you don't want C++0x or Boost, you could use a std::vector (and change the initializer to data(3)), although that's a much more heavyweight solution, its size could be modified from the outside world, and if it is, then the result would result be UB.

提交回复
热议问题