gpt4 book ai didi

C++ vector 问题

转载 作者:行者123 更新时间:2023-11-27 23:25:47 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com