我有一个带有一些对象的 vector 。 我注意到,当我使用删除方法从 vector 中删除一个元素时,我得到了对错误元素的析构函数调用(总是到最后一个元素)。 这是一个产生错误输出的最小示例。
// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Test {
public:
Test(string value) {
_value = value;
cout << "Constructor:" << _value << endl;
}
Test(const Test &t) {
_value = t._value;
cout << "Copied:" << _value << endl;
}
~Test() {
cout << "Destructor:" << _value << endl;
}
string print() {
return _value;
}
string _value;
};
int main()
{
vector<Test> vec;
vec.reserve(3);
cout << "Creation" << endl << endl;
vec.push_back(Test("1"));
vec.push_back(Test("2"));
vec.push_back(Test("3"));
cout << endl << "Deleting" << endl << endl;
vec.erase(vec.begin()); // Here is called the element with value "3"
vec.erase(vec.begin()); // Here is called the element with value "3"
cout << endl << "Log" << endl << endl;
// But the final log print "3"
for (unsigned i = 0; i < vec.size(); i++) {
cout << vec[i].print()<<endl;
}
return 0;
}
输出为:
Creation
Constructor:1
Copied:1
Destructor:1
Constructor:2
Copied:2
Destructor:2
Constructor:3
Copied:3
Destructor:3
Deleting
Destructor:3 <-- WRONG, NEED TO BE 1
Destructor:3 <-- WRONG, NEED TO BE 2
Log
3
Destructor:3
我可以在不改变容器 vector 的情况下解决这个问题。
最佳答案
vec.erase(vec.begin());
不会破坏第一个元素。它通过使用移动或复制赋值运算符将所有后续的移动一个位置来覆盖它。 last 元素被移出后剩下的内容将被破坏,这就是您所观察到的。
关于c++ - vector 删除调用了错误的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58436436/