aligned_storage 与 __attribute__ ((aligned ()))


#include <stdio.h>
#include <memory.h>

#include <iostream>
#include <type_traits>
#include <string>
 
template<class T, std::size_t N>
class static_vector
{
    // N 个 T 的正确对齐的未初始化存储
    typename std::aligned_storage<sizeof(T), alignof(T)*4 >::type data[N];
    std::size_t m_size = 0;
 
public:
    // 于对齐存储创建对象
    template<typename ...Args> void emplace_back(Args&&... args) 
    {
        if( m_size >= N ) // 可行的错误处理
            throw std::bad_alloc{};
        new(data+m_size) T(std::forward<Args>(args)...);
        ++m_size;
    }
 
    // 访问对齐存储中的对象
    const T& operator[](std::size_t pos) const 
    {
        // 注意: C++17 起需要 std::launder
        return *reinterpret_cast<const T*>(data+pos);
    }
 
    // 从对齐存储删除对象
    ~static_vector() 
    {
        for(std::size_t pos = 0; pos < m_size; ++pos) {
            // 注意: C++17 起需要 std::launder
            reinterpret_cast<T*>(data+pos)->~T();
        }
    }
};

struct str_vec
{
    char data[10];
}__attribute__ ((aligned (32)));
 
int main()
{
    //using aligned_storage for std::string in c++
    printf("using aligned_storage for std::string in c++\n");
    static_vector<std::string, 10> v1;
    v1.emplace_back(5, '*');
    v1.emplace_back(10, '*');
    std::cout << &v1[0] << '\n' << &v1[1] << '\n'<<"string align: " << alignof(std::string) <<"\n"<<std::endl;

    //using __attribute__ ((aligned ())) for std::string in c
    printf("using __attribute__ (aligned ()) for std::string in c\n");
    struct str_vec aa[2];
    strcpy(aa[0].data, "*****"); 
    strcpy(aa[1].data, "**********"); 
    printf("%p\n%p\n", &aa[0], &aa[1]);
}
输出:

using aligned_storage for std::string in c++
0x7ffc6079f700
0x7ffc6079f720
string align: 8

using __attribute__ (aligned ()) for std::string in c
0x7ffc6079f6c0
0x7ffc6079f6e0
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值