简体   繁体   English

为指向结构向量的指针分配内存

[英]Allocate memory for a pointer to vector of structs

I have a structure PWS:我有一个结构 PWS:

struct PWS{
    uint64_t key;
    char* value;
    uint64_t timestamp;
    uint64_t txn_id;
};

I want to create a pointer to a vector of PWS to populate it later in my code.我想创建一个指向 PWS 向量的指针,以便稍后在我的代码中填充它。 Is this way correct?这种方式正确吗?

int total_no_of_items = 100000;
vector<PWS> * pws = (vector<PWS>*) _mm_malloc(sizeof(vector<PWS>*) * total_no_of_items, 0);

Unfortunately this is incorrect.不幸的是,这是不正确的。 You are allocating 100000 uninitialized pointers to vector<PWS> , not a vector of structs.您正在为vector<PWS>分配 100000 个未初始化的指针,而不是结构向量。 If you want to allocate a vector of structs that would be as simple as:如果你想分配一个结构向量,就像这样简单:

vector<PWS> pws(total_no_of_items);

If you want the vector itself be heap-allocate (for whatever strange reason), then that would be:如果您希望向量本身是堆分配的(出于任何奇怪的原因),那么这将是:

unique_ptr<vector<PWS>> pws(new vector<PWS>(total_no_of_items));

Also it's unclear why you're trying to use _mm_malloc .此外还不清楚您为什么要尝试使用_mm_malloc If your goal is to load your struct with some SIMD instructions, then you should specify the alignment on the struct:如果您的目标是使用一些 SIMD 指令加载结构,那么您应该在结构上指定对齐方式:

struct alignas(16) PWS { ... }; // aligned for xmm

std::vector 's allocator will take care of the rest. std::vector的分配器将负责其余的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM