#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