std::带有数据交换的矢量指针

std::vector pointer with data swap

本文关键字:指针 数据 std 交换      更新时间:2023-10-16

在下面的代码部分中,交换后得到的内存结构是什么?会不会因为它们交换了下面的内存地址而发生泄漏?因为他们做了深度复制,这会好吗?如果这段代码被卡在一个类中,而我正在用一块动态内存交换一个工作缓冲区,该怎么办?

#include <iostream>
#include <vector>
int main()
{
    std::vector<std::string> * ptr_str_vec =
        new std::vector<std::string>();
    ptr_str_vec->push_back("Hello");
    std::vector<std::string> str_vec;
    str_vec.push_back("World");
    ptr_str_vec->swap(str_vec);
    delete ptr_str_vec;
    //What would be the resulting structures?
    return 0;
}

编辑:发布了轻微错误的代码。修复了错误。

创建向量时,向量使用的底层连续数据块默认是从堆中创建的。在您的情况下,由于您没有提供分配器,所以使用默认的分配器。

int main()
{
    std::vector<std::string> * ptr_str_vec =
        new std::vector<std::string>(); // #^&! *ptr_str_vec is allocated from heap. vector's data block is allocated from heap.
    ptr_str_vec->push_back("Hello");    // #^&! "hello" is copied onto heap block #1
    std::vector<std::string> str_vec;   // #^&! str_vec is allocated from stack. vector's data block is allocated from heap.
    str_vec.push_back("World");         // #^&! "world" is copied onto heap block #2
    ptr_str_vec->swap(str_vec);         // #^&! swap is fast O(1), as it is done by swapping block #1 and #2's address. No data copy is done during swap.
    delete ptr_str_vec;                 // #^&! delete ptr_str_vec as well as heap block #2.
    //What would be the resulting structures? /
    return 0;                           // #^&! delete str_vec as well as heap block #1
}

每个矢量中的值将被交换http://www.cplusplus.com/reference/vector/vector/swap/

我没有看到内存泄漏(除了你的程序在main结束时得到的泄漏,因为你没有删除指针),你的ptr_sr_vec指针不会改变,只有它指向的向量内的数据会改变

假设您已经熟悉了swap,是否有任何原因没有设置它,以便您可以测试输出,看看它自己做了什么?这将是向自己保证你确切知道它在做什么以及你使用它是否合适的最快方法。

在这种情况下,得到的结构简单地是ptr_str_vec指向包含std::string("World")的向量,而str_vec是包含std::string("Hello")的向量。你的例子在回答你的问题时有很多错误,特别是因为每个向量中只有一个元素(因此向量的长度相等),以及因为元素的大小完全相同(因此向量占用的内存段大致相等)。在整个项目的运行实例中,这些条件很可能都不成立。