【问题标题】:std::vector pointer with data swap带有数据交换的 std::vector 指针
【发布时间】:2013-07-17 19:44: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;
}

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

【问题讨论】:

  • 因为你newed 了一些东西而没有调用delete,所以存在泄漏。
  • 假设 ptr_str_vec 被删除,是否还有泄漏?
  • 您显然在调试器下尝试过此操作并亲眼看到了答案。真正的问题是什么?
  • vector::swap 交换向量的内容;您的代码中不存在交换向量的地址这样的事情。
  • 不,不会有泄漏。

标签: c++ pointers memory-leaks new-operator stdvector


【解决方案1】:

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

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
}

【讨论】:

  • 我忘记了使用堆的分配器。谢谢。
【解决方案2】:

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

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

【讨论】:

  • 这是否受到新运营商的影响?
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 2012-04-19
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 2020-05-19
    • 2017-11-13
    • 2016-02-12
    相关资源
    最近更新 更多