lundi 26 octobre 2020

Pushing an array of pointers into a std::vector avoiding copying the objects with push_back

In this code, an array of pointers newData is created in a for loop then it is pushed into a vector testData. The pointers are stored in the vector std::vector<testData*>.

My concern is that I need to make sure that the objects referenced by the pointers remain valid while the vector holds a reference to them, do I lose this reference by calling the line newData = new unsigned char[frameSize]; in a for loop?

I mainly want to avoid copying the objects with a push_back.

How can I create an array of unsigned char* of random char (here I just use 'a') and then push these arrays to a vector?

int numFrames = 25;
int frameSize = 100;

std::vector<unsigned char*> testData;

unsigned char *newData;

for (int i = 0; i < numFrames; i++) {
    newData = new unsigned char[frameSize];

    for (int j = 0; j < frameSize; j++) {
        newData[j] = 'a'; // fill the frame with random data, 'a' here
    }

    testData.push_back(newData);
    newData = 0; // ??
    memset(&newData, 0, frameSize); // ??
}

std::cout << " testData " << testData.size() << "\n";



Aucun commentaire:

Enregistrer un commentaire