2016-05-15 8 views
2

sizeof演算子のstd :: aligned_storageとstd ::次のコードを考えるaligned_union

#include <iostream> 
#include <type_traits> 

int main() { 
    std::aligned_storage<sizeof(double), alignof(double)> storage; 
    std::aligned_union<sizeof(double), double> union_storage; 
    std::cout << sizeof(storage) << '\n'; 
    std::cout << sizeof(union_storage) << '\n'; 
    std::cout << sizeof(double) << '\n'; 
} 

を私は、彼らがdoubleを保持できるようにする必要がありますので、sizeof(storage)sizeof(union_storage)が大きいかsizeof(double)に等しくなるように期待しています。しかし、I get the output

1 
1 
8 

打ち鳴らす-3.8とgcc-5.3の両方が、この出力を生成します。
なぜsizeofが正しくないサイズを返すのですか?
doublestorageまたはunion_storageに配置するために新しい配置を使用すると、それは未定義の動作になりますか?

答えて

9

std::aligned_storageおよびstd::aligned_unionは、記憶の実際のタイプであるメンバーtypeを提供する型形質である。 したがって、typedefメンバだけの空の型であるため、実際のtrait型のメモリに倍精度浮動小数点型を配置することは実際にUBになります。

#include <iostream> 
#include <type_traits> 

int main() 
{ 
    using storage_type = 
     std::aligned_storage<sizeof(double), alignof(double)>::type; 
    using union_storage_type = 
     std::aligned_union<sizeof(double), double>::type; 

    storage_type storage; 
    union_storage_type union_storage; 

    std::cout << sizeof(storage_type) << '\n'; 
    std::cout << sizeof(union_storage_type) << '\n'; 
    std::cout << sizeof(storage) << '\n'; 
    std::cout << sizeof(union_storage) << '\n'; 
    std::cout << sizeof(double) << '\n'; 
    return 0; 
} 

This gives

8 
8 
8 
8 
8 

注:@のT.Cとして。 C++ 14はstdタイプの形質(std::aligned_storage<L, A>::type === std::aligned_storage_t<L,A>)に対して_tで終わるエイリアステンプレートを提供します。メリットは、テンプレートに依存するコンテキストで

  1. Noです。
  2. 少ないタイピング。 ;)
+2

C++の 'aligned_storage_t'などです。 –

関連する問題