C++ vector 问题

标签 c++ vector

我正在使用 std::vector 来保存一些具有动态分配成员的对象,当我将事物放入 vector 时,发生了一些我不理解的事情。

  1. 我调用了 push_back() 并使用对象的构造函数作为参数,但出于某种原因它转到了对象的析构函数。为什么是这样;应该是加而不是删?

  2. 我第二次调用 push_back() 执行与之前相同的操作,但这次它在 dbgdel.cpp operator delete (第 52 行)。但永远不应在构造函数或 push_back() 中调用 delete。

我不确定哪些代码部分与这个问题相关,因为有问题的行在方法中非常根深蒂固。

编辑:添加代码

class Thing{
    int** Array;
    int size;   // of square array
    Point current; // location
    Thing(int _n){
        // allocates, and gives values to the array, and members
        // only constructor
    }
};
class ThingMgr{
    Thing * Control;
    Thing * Current;
    Thing * Previous;
    int size;  // size of all. same use as in Thing
    ThingMgr(int _n){
        size = _n;
        Control = new Thing(size);
        Current = new Thing(size);
        Previous = new Thing(size);
    }
    void rearrange(int _num){
        std::vector<Thing> possibles;

        // performs deterministic work on members

        // [0] first
        possibles.push_back(Thing(size)); // this succeeds
        // [1] second
        possibles.push_back(Thing(size)); // this fails

        // more operations to be performed never reached.
    }
};

最佳答案

first: I call push_back() and use the constructor of the objects as the argument, but for some reason it goes to the destructor of the object. why is this; it should be adding not deleting?

您正在将该元素的拷贝 推送到vector 中。您构建一个时间元素,调用其复制构造函数以在 vector 中创建一个拷贝,然后调用时间元素的析构函数。

second: I call push_back() a second time doing the same as before, but this time it throws an illegal memory access at dbgdel.cpp operator delete (line 52). but delete should never be called in a constructor, or push_back().

奇怪的是,第二次调用时会发生这种情况,但最终当 vector 需要重新生长时,它会再次复制元素。

您可能没有为相关元素提供适当的复制构造函数。

关于C++ vector 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9609689/

相关文章:

c++ - #定义: why uppercase?

c++ - 拥有大量重载的类构造函数是否被认为是不好的编程实践?

c++ - 如何根据构造函数参数为类成员函数模板化代码

c++ - MPI 发送/接收 vector

c++ - 从 std::function 的 vector 中移除一个项目

c++ - Valgrind显示内存泄漏? ffff可能与相关吗?

c++ - 将函数导出到没有类的 DLL

c++ - std::vector 对于清除或删除 POD 的行为是否不同

c++ - 使用迭代器访问 vector 的特定点

c++ - vector 删除多个区域,2次删除与单次分配?