gabriel gabriel - 5 months ago 35
C++ Question

std::vector inside MFC CArray - getting "iterator not dereferencable" error after adding elements to the CArray

In our code we use both stl and MFC containers. I've encountered a case where we have a CArray of objects, where each object contains an std::vector.

After adding several objects to the CArray, so that the data in the CArray will be reallocated and copied when it reaches it's maximum size, it seems like the inner vector is corrupted. When I iterate over the CArray and for each object iterate over the std::vector, I get a "vector iterator not dereferencable" error.

I looked at the MFC code and it uses memcpy() to copy the data after reallocating. In the std::vector (I use visual studio) there is member called _Myproxy which has a member called _Mycont which seems to change it's value in the new vector (the vector that was copied by memcpy()).

I replicated this issue, I'm attaching the sample code below.

I can refactor this code and I will probably do so, but I want to understand exactly what's happening.

#include "stdafx.h"

#include <vector>
#include <iostream>

// an object which holds an std::vector
class test_t
test_t() {}

std::cout << "d'tor" << std::endl;

void add(int 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;

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];

for (int i = 0; i < arr.GetSize(); ++i)
test_t& rt = arr[i];
rt.print(); // error occurs here



CArray doesnt play well with non-POD types, relying on memcpy_s when resizing. You can make it work, but in general it's best avoided for this use case.

See the note here: