4
\$\begingroup\$

When trying to determine the size of glm::vec3 (from GLM math library) by using the size of operator like so:

sizeof(glm::vec3)

I get 12 returned. When I look at the definition of a vec3 struct I see this:

    template <typename T, precision P = defaultp>
    struct tvec3
    {
        // -- Implementation detail --

        typedef tvec3<T, P> type;
        typedef tvec3<bool, P> bool_type;
        typedef T value_type;

#       ifdef GLM_META_PROG_HELPERS
            static GLM_RELAXED_CONSTEXPR length_t components = 3;
            static GLM_RELAXED_CONSTEXPR precision prec = P;
#       endif//GLM_META_PROG_HELPERS

        // -- Data --

#       if GLM_HAS_ANONYMOUS_UNION
            union
            {
                struct{ T x, y, z; };
                struct{ T r, g, b; };
                struct{ T s, t, p; };

#               ifdef GLM_SWIZZLE
                    _GLM_SWIZZLE3_2_MEMBERS(T, P, tvec2, x, y, z)
                    _GLM_SWIZZLE3_2_MEMBERS(T, P, tvec2, r, g, b)
                    _GLM_SWIZZLE3_2_MEMBERS(T, P, tvec2, s, t, p)
                    _GLM_SWIZZLE3_3_MEMBERS(T, P, tvec3, x, y, z)
                    _GLM_SWIZZLE3_3_MEMBERS(T, P, tvec3, r, g, b)
                    _GLM_SWIZZLE3_3_MEMBERS(T, P, tvec3, s, t, p)
                    _GLM_SWIZZLE3_4_MEMBERS(T, P, tvec4, x, y, z)
                    _GLM_SWIZZLE3_4_MEMBERS(T, P, tvec4, r, g, b)
                    _GLM_SWIZZLE3_4_MEMBERS(T, P, tvec4, s, t, p)
#               endif//GLM_SWIZZLE
            };

         //other code......
       }

For which I see three structs, each with three member variables of templated type T, which in GLM defaults to float type. My question is why is the sizeof() operator returning 12 bytes as the size of glm::vec3 when it looks like it should be 36 bytes:

3 structs, with 3 float members each = 3*3*4(number of bytes in a float) = 36.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Padded for performance \$\endgroup\$
    – concept3d
    Jul 24, 2017 at 17:57
  • 5
    \$\begingroup\$ @concept3d There is no padding. \$\endgroup\$ Jul 24, 2017 at 19:49

1 Answer 1

9
\$\begingroup\$

The "union" there says that these are three different ways of viewing the same memory.

So the x component of the first struct occupies the same bytes of memory as the r component of the second struct, and so on. The three different versions just create different aliases by which you can refer to the vector's components - depending on whether you're viewing it as a spatial position / offset / direction (xyz), or a colour (rgb), or a parametric coordinate (stp), for instance.

That gives the expected 3 float members * 4 bytes per float = 12 bytes total size.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .