我想知道在c++14中在哪里使用alignof运算符
#include <iostream>
struct Empty {};
struct Foo {
int f2;
float f1;
char c;
};
int main()
{
std::cout << "alignment of empty class: " << alignof(int*) << '\n';
std::cout << "sizeof of pointer : " << sizeof(Foo) <<"\n" ;
std::cout << "alignment of char : " << alignof(Foo) << '\n'
std::cout << "sizeof of Foo : " << sizeof(int*) << '\n' ;
}我想知道alignof在上面的程序中做了什么?
发布于 2015-08-18 04:05:41
有些平台要么不支持读取未对齐的数据,要么读取速度非常慢。您可以结合使用alignof和alignas来创建一个字符缓冲区,该缓冲区适用于存储char以外的其他类型(这就是std::aligned_storage所做的)。例如..。
template<class T, std::size_t N>
class static_vector
{
// properly aligned uninitialized storage for N T's
typename std::aligned_storage<sizeof(T), alignof(T)>::type data[N];
std::size_t m_size = 0;
public:
// Create an object in aligned storage
template<typename ...Args> void emplace_back(Args&&... args)
{
if( m_size >= N ) // possible error handling
throw std::bad_alloc{};
new(data+m_size) T(std::forward<Args>(args)...);
++m_size;
}
// Access an object in aligned storage
const T& operator[](std::size_t pos) const
{
return *reinterpret_cast<const T*>(data+pos);
}
// Delete objects from aligned storage
~static_vector()
{
for(std::size_t pos = 0; pos < m_size; ++pos) {
reinterpret_cast<const T*>(data+pos)->~T();
}
}
};*taken from cppreference example
https://stackoverflow.com/questions/32058533
复制相似问题