C++ alignof运算符有什么用途?

C++ alignof运算符有什么用途?,c++,alignment,c++14,alignof,C++,Alignment,C++14,Alignof,我想知道在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 <&

我想知道在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' ;
}
#包括
结构空{};
结构Foo{
int f2;
浮球f1;
字符c;
};
int main()
{

std::cout某些平台不支持读取未对齐的数据,或者读取数据速度非常慢。您可以使用
alignof
alignas
创建适合存储除
char
以外的其他类型的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();
        }
    }
};
模板
类静态向量
{
//为N T正确对齐的未初始化存储
typename std::aligned_storage::type data[N];
std::size\u t m\u size=0;
公众:
//在对齐存储中创建对象
模板空位置返回(Args&…Args)
{
if(m_size>=N)//可能的错误处理
抛出std::bad_alloc{};

new(data+m_size)T(std::forward

您熟悉数据结构对齐吗?alignof只评估给定类型的对齐。注释(“指针的大小”)和打印的大小(
sizeof(Foo)
)似乎在代码中没有对齐。对齐情况也是如此。事实上,代码似乎不连贯。