首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >alignof运算符的用途是什么?

alignof运算符的用途是什么?
EN

Stack Overflow用户
提问于 2015-08-18 03:50:13
回答 1查看 1.1K关注 0票数 0

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

代码语言:javascript
复制
#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在上面的程序中做了什么?

EN

回答 1

Stack Overflow用户

发布于 2015-08-18 04:05:41

有些平台要么不支持读取未对齐的数据,要么读取速度非常慢。您可以结合使用alignofalignas来创建一个字符缓冲区,该缓冲区适用于存储char以外的其他类型(这就是std::aligned_storage所做的)。例如..。

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32058533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档