简体   繁体   中英

c++ memory allocation vector of pointers

I am parallelizing code, thus using structure parallel_vector (ppl). The question would be the same with standard 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).

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 ? should i delete Block_temp at the end of the current loop, or would this destroy the object that is contained in the vector ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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