Llamar a push_back en un std :: vector de objetos (no punteros) tiene efectos secundarios graves. Entonces, ¿serían mejores los punteros?

This follows on from my previous question, where I was slow to supply all the information so I am creating a new question in the hope of more input. Given:

    struct otherClass {
        ImportantObj    *ptrToImpObj;
        otherClass() {ptrToImpObj = NULL;}
    struct anEntry {
        Thing *thing;
        std::vector<otherClass> *iDM2P2H;
        anEntry(Thing *tg, std::vector<sqdDMPair> *dM2Pair = NULL)
            : thing(tg), iDM2P2H(dM2Pair) {}
        ~anEntry() {delete iDM2P2H;}
    std::vector<anEntry *> aQueue;
    std::vector<anEntry> bQueue;
    void aMethod () {
        Thing thingy = &(masterArrayOfThings[42]);
        aQueue.push_back(new anEntry(thingy, iDM2P2H));
    void bMethod () {
        Thing thingy = &(masterArrayOfThings[42]);
        bQueue.push_back(anEntry(thingy, iDM2P2H));

The second method will invoke the dtor on the memory shared between the two objects involved with the copy constructor.

In this case I feel I should be using pointers inside my vector and aQueue is preferable to bQueue.



Let's say I'll have 20 aQueue's and they will be cleared and iDM2P2H reemplazado centenares (thousands?) of times a second as the AI route evaluation sees fit.

preguntado el 27 de agosto de 11 a las 23:08

1 thing at a time. Your anEntry class is horrible. Fix that first. -

I mean make it handle it's resources properly. Lee esto para principiantes. -

Rather than following the "rule of 3" and deep copying to satisfy my dtor, it would be more maintainable to use pointers in the stead of objects. -

You need reference-counting then. -

@John, you should follow the "rule of 3" OR forbid access to the copy constructor/operator=. Failing to implement all three but still leaving the default implementations in place is a bug waiting to happen. -

4 Respuestas

About deletion of iDM2P2H, either now or ever in the future, your program is going to cause that error. If you set the same pointer in two objects, sooner or later they will both die and their destructors will try to delete the same memory. If you use pointers and new the objects, the problem persists when you delete the anEntry objetos.

The solution is simply to avoid deleting iDM2P2H en el objeto anEntry destructor, and delete it in the same context of whoever created it. That is for example if it was created at program startup, you could delete it when you have finished your need for it, in the main execution path of the program.

Respondido 28 ago 11, 03:08

Tu problema aquí es tu anEntry copy constructor is broken. The default copy constructor (anEntry (const anEntry &)) simply copies all members; with your class's explicit destructor, this results in double freeing. The same applies for the default operator=. Por el Regla de tres, if you define any one of a destructor, copy constructor, and operator=, you should generally implement the other two (or forbid them by making them private and unimplemented); otherwise there's a good chance the default implementation of one of them will cause problems like this.

Ahora, la vector class requires a working copy constructor. This is part of the vector contract. If your class has a missing (ie, forbidden by making it private) copy constructor, the compiler will error out, preventing these "serious side effects". If the class has a roto copy constructor, well, that's not vectores culpa

Note that you may want to consider using RAII-style allocation in your anEntry class. For example, make iDM2P2H a std::vector<otherClass> en lugar de std::vector<otherClass> *. By doing so, you won't need a destructor en absoluto, and if the default copy semantics are acceptable to you, you might be able to do with the default copy constructor in this case.

Dicho esto, las vector's copying may indeed entail significant overhead at times. There are a number of things you can do to work around this; however I would recommend en contra un crudo std::vector<anEntry *> - the reason being that this won't clean up the pointed-to elements automatically.

En su lugar, use un std::vector<std::unique_ptr<anEntry>> (if you have a C++0x compiler) or boost::ptr_vector<anEntry>. This will give you the automatic destruction benefits of vector but will not copy any elements (as the vector is a vector of pointers to objects). Note that in the unique_ptr case you will need to utilizado std::move to add elements to the vector.

Alternately, if your compiler supports C++0x move-aware containers, you could write a move constructor:

struct anEntry {
    Thing *thing;
    std::vector<sqdDMPair> iDM2P2H;

    anEntry(Thing *thing_, std::vector<sqdDMPair> *vec = NULL)
      : thing(thing_), iDM2P2H(vec ? *vec : std::vector<sqdDMPair>())
    { }

    // Default copy constructor and destructor OK

    // Move constructor
    anEntry(anEntry &&src)
      : thing(src.thing), iDM2P2H(std::move(src.iDM2P2H)) { }

    anEntry &operator=(anEntry &&other) {
      if (this != &other) {
        thing = other.thing;
        iDM2P2H = std::move(other.iDM2P2H);

Usar std::move allows the contents of iDM2P2H to be moved to the new position in the outer vector without copying recursively. However, C++0x support is still in its infancy, and your compiler and STL may or may not support it yet (if std::vector<std::unique_ptr<int>> compiles, you're probably ok).

contestado el 23 de mayo de 17 a las 15:05

Or std::tr1::shared_ptr. Less good than C++0x, but better than Boost. - Nemo

Sorry, I hadn't written the copy ctor as it would be easier not to have use of it. - John

@John, if you don't want the copy ctor, fine, bórralo. Boost has a nice boost::noncopyable class for this. But don't leave a copy constructor around that will silently cause heap corruption if you accidentally use it :) - bdonlan

It depends on how expensive and big your objects are. Having a vector of objects is ok if they're small, but if they're big or expensive1, all the copying/constructing/destructing can add up to a large performance hit, in which case you should use pointers (and then you have to manage the memory for all the objects, etc).

1 A class can be small and expensive if it doesn't have many data members (so it's not big in size) but manages expensive resources that are changed when it is copied, destroyed, or created.

Respondido 28 ago 11, 03:08

If you really have objects that contain pointers to shared data/resources, maybe you could consider using std::shared_ptr<my_shared_type> rather than just having delete llamado en el dtor.

Usar std::vector<> of pointers might make the issues go away for awhile, but it's potentially just masking a more fundamental issue of shared resource management.

Espero que esto ayude.

Respondido 28 ago 11, 03:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.