如果我使用动态分配的数组初始化 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/