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

标签 c++ arrays memory vector

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

相关文章:

c++ - 结构 C++ 中的函数

php - 使用数组 SQL 获取 ID

arrays - 在排序数组中找到所有对 (x, y) 使得 x + y < z

c - 保护 VirtualAlloc 分配的内存中的各个页面

ios - 尽管删除了图像,但 UIImageView 数据仍然存在

c++ - 使用 Winsock 客户端在本地网络上出现错误 11004

c++ - 使用 wmemset 初始化 wchar_t 数组。编码重要吗?

python - 指定 numpy.datype 来读取 GPX 轨迹点

c - 段错误 : Cannot access memory at address

c++ - stbi_load 不返回任何值