On alignment

Gabriel Dos Reis gdr@integrable-solutions.net
Wed Apr 23 19:33:00 GMT 2003


Tom Tromey <tromey@redhat.com> writes:

| >>>>> "Jason" == Jason Merrill <jason@redhat.com> writes:
| 
| [ about  struct foo { double x; } ]
| 
| Tom> I'd like to find the most future-proof way to do this.  In the above,
| Tom> is __alignof__(foo::x) the best way?  I'm only concerned with
| Tom> alignment of fields.
| 
| Jason> It is since my recent patch to do all alignment calculation for
| Jason> fields in layout_decl.
| 
| I can't do this.
| 
|     struct aligner { double field; };
| 
|     int compute () { return __alignof__ (aligner::field); }
| 
| fleche. gcc -c y.cc
| y.cc: In function `int compute()':
| y.cc:1: error: invalid use of non-static data member `aligner::field'
| y.cc:3: error: from this location

The following does the job:

    template<typename T>
      struct object_alignment {

         struct helper {
            T& datum;
            helper();
         };

         static helper instance;

         enum { value = __alignof__ (instance.datum) };
      };

To be used as object_alignment<T>::value.

| I can use __alignof__(aligner), but my concern is that eventually this
| will yield "8" instead of "4" on x86.

With the above, the following

     #include <iostream>

     int main()
     {
        std::cout << object_alignment<double>::value
                  << std::endl;
     }

outputs "8" on an i686-pc-linux-gnu.

Enjoy ;-)

-- Gaby



More information about the Gcc mailing list