简体   繁体   English

c ++指针的内存分配向量

[英]c++ memory allocation vector of pointers

I am parallelizing code, thus using structure parallel_vector (ppl). 我正在并行化代码,因此使用结构parallel_vector(ppl)。 The question would be the same with standard std::vector... 问题与标准的std :: vector相同......

I first build a vectors of pointer to structs. 我首先构建一个指向结构的指针向量。 Struct is huge, with primitive types members alongside with huge arrays of primitive type (23000 elements). 结构是巨大的,原始类型成员与巨大的原始类型数组(23000个元素)一起。

I implemented a deep copy copy constructor for this struct. 我为这个结构实现了一个深拷贝拷贝构造函数。

Then, i access elements in this list in a loop. 然后,我循环访问此列表中的元素。

for (int ii=0; ii < nbBlocks; ii++)
{
    MyStruct* Block_temp = list_structs.at( ii );
    // ...
}

When i access element at position ii, am I creating a new object with memory allocation ? 当我访问位置ii的元素时,我是否创建了一个具有内存分配的新对象? should i delete Block_temp at the end of the current loop, or would this destroy the object that is contained in the vector ? 我应该删除当前循环结束时的Block_temp,还是会破坏向量中包含的对象?

Thanks 谢谢

You have a pointer to what is already in the vector, the vector seems to own your data, so do not delete it. 你有一个指向已经在向量中的内容的指针,向量似乎拥有你的数据,所以不要删除它。 Copying a pointer is not an allocation. 复制指针不是分配。

Consider: 考虑:

int* a = new int;
int* b = a; // Pretty much what you are doing
delete a; // If you deleted b, then this would be a double delete, and using a or b after that point would be bad

See the docs for std::vector::at 请参阅std :: vector :: at的文档

http://www.cplusplus.com/reference/vector/vector/at/ http://www.cplusplus.com/reference/vector/vector/at/

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

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