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),
No, this is undefined behaviour, for two reasons:
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.