2013-09-24 8 views
8

私はalignasをどのように使うべきかを理解しようとしていますが、プラグマパックの代わりに使うことができるのだろうか、私はそれを検証するのに苦労しましたが運がないと思います。 gcc 4.8.1(http://ideone.com/04mxpI)を使用すると、プラグマを使用しているときは5バイトですが、私は常にSTestAlignas以下で8バイトを取得します。私はsizeof(STestAlignas)が5を返すようにしたいと思います。3.3(http://gcc.godbolt.org/)でこのコードを実行しようとしましたが、エラーが発生しました:プラグマパックを置き換えるためにalignasを使用するには?

!!エラー:要求された位置合わせが8 'long'とタイプしてください。

alignasのアライメント値は最小値ですか?以下

私のテストコードです:GCC 4.8.1のための

#include <iostream> 
#include <cstddef> 
using namespace std; 

#pragma pack(1) 
struct STestPragmaPack { 
    char c; 
    long d; 
} datasPP; 
#pragma pack() 

struct STestAttributPacked { 
    char c; 
    long d; 
} __attribute__((packed)) datasAP; 

struct STestAlignas { 
    char c; 
    alignas(char) long d; 
} datasA; 

int main() { 
    cout << "pragma pack = " << sizeof(datasPP) << endl; 
    cout << "attribute packed = " << sizeof(datasAP) << endl; 
    cout << "alignas = " << sizeof(datasA) << endl; 
} 

結果:

pragma pack = 5 
attribute packed = 5 
alignas = 8 
+0

'の#pragma pack'永遠に非ポータブル拡張されます。アーキテクチャによっては、アライメントされていないメモリアクセスをサポートしていないものもあります。 –

答えて

10

alignas#pragma packを置き換えることはできません。

GCCはalignas宣言を受け入れますが、厳密な位置合わせ要件(この場合はlong)を満たしていれば、指定した要件も満たします。標準は、実際に明示的に段落5、§7.6.2でこれを禁止して

しかし、GCCはあまりにも寛大である:私は思う

The combined effect of all alignment-specifiers in a declaration shall not specify an alignment that is less strict than the alignment that would be required for the entity being declared if all alignment-specifiers were omitted (including those in other declarations).

関連する問題