alignof运算符有什么用?

时间:2015-08-17 19:50:13

标签: 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 << "sizeof of pointer : "    << sizeof(Foo) <<"\n" ;
    std::cout << "alignment of char : "       << alignof(Foo)  << '\n'
    std::cout << "sizeof of Foo : "        << sizeof(int*)   << '\n' ;
}

我想知道alignof在上述程序中做了什么?

1 个答案:

答案 0 :(得分:2)

某些平台要么不支持读取未对齐的数据,要么实际上很慢。您可以将alignofalignas一起使用来创建适合存储除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