gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:25:19 25 4
gpt4 key购买 nike

如果我用一个动态分配的数组初始化一个 vector ,然后 vector 超出范围并被释放, vector 是否从它包装的数组中释放内存?更具体地说,假设我有一个示例函数:

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

当从函数返回的 vector 超出范围或被手动释放时,底层动态分配的数组是否也会释放其内存?

最佳答案

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

vector 根本不包装数组。

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?

没有。您正在使用将 2 个迭代器作为输入的构造函数来构造 vector 。它遍历源数组,将其元素的值复制到 vector 的内部数组中。源数组本身是独立的,必须在 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;
}

或者:

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

关于使用数组初始化时的 C++ STL vector 内存管理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57049368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com