0

我想知道alignof在 c++14 中在哪里使用运算符

#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上面的程序有什么作用?

4

1 回答 1

2

一些平台要么不支持读取未对齐的数据,要么这样做的速度很慢。您可以使用alignofwithalignas创建一个适合存储其他类型的字符缓冲区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();
        }
    }
};

*取自 cppreference 示例

于 2015-08-17T20:05:40.643 回答