[英]Is it possible to have a std::vector<char> allocate memory with a chosen memory alignment
I am copying a process' memory in a vector<char>
buffer and would like the memory allocated for this vector to have a higher alignment than just the default. 我正在
vector<char>
缓冲区中复制进程的内存,并希望为此向量分配的内存具有比默认值更高的对齐。
This is because I am looking for arbitrarily typed patterns in that buffer where memory could represent anything - I expect any value/type pair I am looking for to be aligned according to it's type. 这是因为我在缓冲区中寻找任意类型的模式,其中内存可以代表任何东西 - 我希望我正在寻找的任何值/类型对根据它的类型进行对齐。
Maybe I could resolve this using an 'offset' but I'd rather have my char buffer be aligned. 也许我可以使用'offset'解决这个问题,但我宁愿让我的char缓冲区对齐。
Is there any way to do this other than creating a vector<large_type>
instead? 除了创建一个
vector<large_type>
之外,还有什么方法可以做到这一点吗?
I could solve my issue with a custom allocator . 我可以用自定义分配器解决我的问题。
Example with boost::alignment::aligned_allocator
使用
boost::alignment::aligned_allocator
#include <vector>
#include <boost/align/aligned_allocator.hpp>
template <typename T>
using aligned_vector = std::vector<T, boost::alignment::aligned_allocator<T, 16>>;
// 16 bytes aligned allocation
See also How is a vector's data aligned? 另请参见矢量数据如何对齐? .
。
I had used something like the following for this purpose: 我为此目的使用了类似的东西:
#include <iostream>
#include <vector>
template<typename T>
class AlignedVector {
public:
AlignedVector() : data_(nullptr) {}
AlignedVector(int n)
: char_vec_(sizeof(T)*(n+1)),
data_(AlignedAddr(char_vec_.data())),
size_(n) {}
T* operator[](size_t n) { return data_[n]; }
const T* operator[](size_t n) const { return data_[n]; }
T* data() { return data_; }
const T* data() const { return data_; }
size_t size() const { return size_; }
void resize(size_t n) {
char_vec_.resize(sizeof(T)*(n+1));
data_ = AlignedAddr(char_vec_.data());
size_ = n;
}
private:
static T* AlignedAddr(char* addr) {
return (T*)(addr + sizeof(T) - ((size_t)addr % sizeof(T)));
}
std::vector<char> char_vec_;
T* data_;
size_t size_;
};
int main()
{
AlignedVector<int[128]> vec(13);
std::cout << (size_t)vec.data() << std::endl;
}
The main function that performs the alignment is static T* AlignedAddr(char* addr)
. 执行对齐的主要功能是
static T* AlignedAddr(char* addr)
。 Basically for an N-element type T
array we allocate enough size for (N+1) elements and return the lowest aligned address inside the allocated area. 基本上对于N元素类型
T
数组,我们为(N + 1)个元素分配足够的大小,并返回分配区域内的最低对齐地址。
To enable other methods in std::vector<T>
one would need to implement them using data_
and size_
individually. 要在
std::vector<T>
启用其他方法,需要单独使用data_
和size_
来实现它们。 This worked for me since I usually only use few of them. 这对我有用,因为我通常只使用其中的一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.