![](/img/trans.png)
[英]Difference between sizeof(empty struct) and sizeof(struct with empty array)?
[英]sizeof aligned empty struct
我发现,对齐的空结构的大小严格等于其对齐( 实时示例 ):
#include <iostream>
#include <utility>
#include <cstdlib>
template< std::size_t i >
struct alignas(1 << i) aligned_storage
{
};
template< std::size_t ...I >
constexpr
void
test(std::index_sequence< I... >)
{
static_assert(((sizeof(aligned_storage< I >) == (1 << I)) && ...));
}
int
main()
{
test(std::make_index_sequence< 29 >{});
return EXIT_SUCCESS;
}
它是否很好地形成的代码 (特别是放置new
S)(?):
#include <iostream>
#include <algorithm>
#include <cstdlib>
template< std::size_t argument, std::size_t base = 2, bool = (argument < base) >
constexpr std::size_t log = 1 + log< (argument / base), base >;
template< std::size_t argument, std::size_t base >
constexpr std::size_t log< argument, base, true > = 0;
template< typename ...types >
struct alignas(2 << std::max({log< sizeof(types) - 1 >...})) aligned_storage
{
};
struct A
{
int j;
A(int i) : j(i) { std::cout << j << ' ' << __PRETTY_FUNCTION__ << std::endl; }
~A() { std::cout << j << ' ' << __PRETTY_FUNCTION__ << std::endl; }
};
struct B
{
short j;
B(short i) : j(i) { std::cout << j << ' ' << __PRETTY_FUNCTION__ << std::endl; }
~B() { std::cout << j << ' ' << __PRETTY_FUNCTION__ << std::endl; }
};
int
main()
{
aligned_storage< A, B > storage;
auto a = ::new (&storage) A{1};
a->~A();
auto b = ::new (&storage) B{2};
b->~B();
return EXIT_SUCCESS;
}
在C ++中可以使用上面的struct
代替std::aligned_storage_t
吗?
http://en.cppreference.com/w/cpp/language/sizeof
当应用于类类型时,结果是该类对象的大小加上将此类对象放置在数组中所需的任何其他填充。
应用于空类类型时,始终返回1。
等效的解释是sizeof(type[N])==sizeof(type)*N
标准要求始终为true
。 这将导致sizeof
的结果始终是实际内存表示大小和对齐方式中的较大者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.