[Solved] C++ Issues with vector


You did not show the code which adds the Child*s to the vector, but the symptoms you describe provide compelling evidence that you used pointers to some kind of local or temporary objects, which go out of scope (are destroyed) while the vector still holds the pointers.

Your program hangs as a result of using the vtable of a deleted object. (Seg fault would be more likely than hang, but this explanation is still the best fit for the symptoms).

Edit: Now you showed that code and confirmed my guess:

Child child = Child();
Parent* p = &child;
m.v.push_back(p);

There are a lot of pitfalls in using a vector of object pointers the way you do, so just correcting this one bug won’t put you on solid ground. But this one bug is easy to correct:

    Parent* p = new Child();
    m.v.push_back(p);

or depending on what else you might want to avoid changing in code you didn’t show us yet, an uglier (but maybe more compatible) source code for the same run time behavior is:

    Child& child = *( new Child());
    Parent* p = &child;
    m.v.push_back(p);

Either way, the key is that you are creating an object with new that won’t go away until you explicitly delete it, rather than creating a local object that goes away as soon as its name goes out of scope.

One pitfall of your design (and reason an early comment told you to use smart pointers) is the memory leak if you fail to add code to finally delete the objects. In a structure , as you showed, that exists for the life of main() the actually memory leak of failing to clean it up has no consequences and could be safely ignored. But coding and ignoring such leaks is a bad habit that will get you into trouble if you attempt more interesting projects.

0

solved C++ Issues with vector