【发布时间】:2016-08-21 15:13:18
【问题描述】:
在我们的代码中,我们同时使用 stl 和 MFC 容器。我遇到过这样一种情况,我们有一个 CArray 对象,其中每个对象都包含一个 std::vector。
在向 CArray 添加多个对象后,当 CArray 中的数据达到最大大小时将被重新分配和复制,看起来内部向量已损坏。当我遍历 CArray 并为每个对象遍历 std::vector 时,我得到一个“vector iterator not dereferencable”错误。
我查看了 MFC 代码,它使用 memcpy() 在重新分配后复制数据。在 std::vector (我使用 Visual Studio)中有一个名为 _Myproxy 的成员,它有一个名为 _Mycont 的成员,它似乎改变了它在新向量(由 memcpy() 复制的向量)中的值。
我复制了这个问题,我附上下面的示例代码。
我可以重构这段代码,我可能会这样做,但我想确切地了解发生了什么。
#include "stdafx.h"
#include <vector>
#include <iostream>
// an object which holds an std::vector
class test_t
{
public:
test_t() {}
~test_t()
{
std::cout << "d'tor" << std::endl;
}
void add(int i)
{
m_vec.push_back(i);
}
void print()
{
for (std::vector<int>::iterator it = m_vec.begin(); it != m_vec.end(); ++it)
{
int i = *it;
std::cout << i << std::endl;
}
std::cout << std::endl;
}
private:
std::vector<int> m_vec;
};
void test()
{
// array if objects where each object holds an std::vector
CArray<test_t, test_t&> arr;
for (int i = 0; i < 10; ++i)
{
test_t t;
int j = arr.Add(t);
test_t& rt = arr[i];
rt.add(1);
rt.add(2);
rt.add(3);
}
for (int i = 0; i < arr.GetSize(); ++i)
{
test_t& rt = arr[i];
rt.print(); // error occurs here
}
}
谢谢, 加布里埃尔
【问题讨论】: