简体   繁体   English

用数组初始化时的C ++ STL向量内存管理?

[英]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. 不。您正在使用将2个迭代器作为输入的构造函数来构造向量。 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. 源数组本身是分开的,必须在mem_test()退出前显式delete[] ,否则它将被泄漏。

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;
}

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

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