简体   繁体   中英

C++ STL Vector Memory Management When Initialized With Array?

If I initialize a vector with a dynamically allocated array, then later the vector goes out of scope and is to be freed, does the vector free the memory from the array that it is wrapping? More specifically, say I have an example function:

std::vector<float> mem_test() {
    unsigned char* out = new unsigned char[10];
    for (int i = 0; i < 10; i++) {
        out[i] = i * i;
    }
    std::vector<float> test_out(out, out + 10);
    return test_out;
}

int main() {
    std::vector<float> whatever = mem_test();

    // Do stuff with vector

    // Free vector
    std::vector<float>().swap(whatever);
}

When the vector returned from the function goes out of scope or is manually freed, will the underlying dynamically allocated array also have its memory freed?

does the vector free the memory from the array that it is wrapping?

The vector does not wrap the array at all.

When the vector returned from the function goes out of scope or is manually freed, will the underlying dynamically allocated array also have its memory freed?

No. You are constructing the vector using a constructor that takes 2 iterators as input. It iterates through the source array copying the values of its elements into the vector's internal array. The source array itself is keep separate and must be delete[] 'd explicitly before mem_test() exits or else it will be leaked.

std::vector<float> mem_test() {
    unsigned char* out = new unsigned char[10];
    for (int i = 0; i < 10; i++) {
        out[i] = i * i;
    }
    std::vector<float> test_out(out, out + 10);
    delete[] out; // <-- HERE
    return test_out;
}

Alternatively:

std::vector<float> mem_test() {
    std::unique_ptr<unsigned char[]> out(new unsigned char[10]); // <-- auto delete[]'d
    for (int i = 0; i < 10; i++) {
        out[i] = i * i;
    }
    std::vector<float> test_out(out.get(), out.get() + 10);
    return test_out;
}

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