What is the use of alignof operator?

1.4k Views Asked by At

I want to know where to use alignof operator in 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' ;
}

I would like to know what alignof does in above program?

1

There are 1 best solutions below

0
On

Some platforms either don't support reading misaligned data or are really slow at doing so. You can use alignof with alignas to create a char buffer suitable to storing other types than char (this is what std::aligned_storage does). For example...

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