2016-05-15 65 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'; 
} 

我希望sizeof(storage)sizeof(union_storage)为大于或等于sizeof(double),因为他们必须要能够保持double。然而,I get the output

1 
1 
8 

铛-3.8和gcc-5.3都产生此输出。
为什么sizeof返回不正确的尺寸?
如果我使用placement new将double放入storageunion_storage那会是未定义的行为吗?

回答

9

std::aligned_storagestd::aligned_union是提供会员type的类型特征,其是存储的实际类型。 因此,在实际特征类型的内存中放置一个double将确实是UB,因为它们是只有typedef成员的空类型。

#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提供别名模板,其_tstd类型特征(即std::aligned_storage<L, A>::type === std::aligned_storage_t<L,A>)。好处是在模板相关的上下文中,

  1. typename
  2. 减少打字。 ;)
+2

或'aligned_storage_t'等在C++中14。 –

相关问题