矢量擦除调用的错误析构函数
Wrong destructor called by vector erase
我有一个包含一些对象的向量。 我注意到,当我使用 erase 方法从矢量中删除一个元素时,我得到了对错误元素的析构函数调用(总是对最后一个元素(。 下面是一个产生错误输出的最小示例。
// 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
我会在不更改容器向量的情况下解决这个问题。
vec.erase(vec.begin());
不会破坏第一个元素。它通过使用移动或复制赋值运算符将所有后续操作移动到一个位置来覆盖它。最后一个元素被移出后剩下的东西就会被破坏,这就是你正在观察的。
相关文章:
- 不命名构造函数和析构函数上的类型错误
- 导致 Seg 错误的 SingleLinkedList 的析构函数
- LINUX 操作系统上的错误:令牌之前预期的构造函数、析构函数或类型转换'('?
- 矢量擦除调用的错误析构函数
- 在析构函数中调用"delete"运算符时"compiler is out of heap space"编译器错误
- 在Visual Studio中,与std::async一起使用时不调用"thread_local"变量"析构函数,这是一个错误吗?
- 导致堆缓冲区错误的动态分配数组的析构函数
- 非默认析构函数会导致不完整的类型错误
- 析构函数删除错误的元素
- 使用自定义工具集获取动态退出析构函数链接错误 - eh 矢量析构函数
- 使用 boost::thread 运行函子,但析构函数被错误地调用
- 错误 c++ 在令牌之前'('预期的构造函数、析构函数或类型转换
- 错误:在“(”标记之前进行预期的构造函数、析构函数或类型转换.即使我有一个构造函数
- 模板类中的析构函数给出错误
- 在析构函数内取消引用指针时出现分段错误
- 模板化子类析构函数中的隔离错误
- GCC 9.1 返回 void& 作为显式析构函数调用的结果类型。这是一个错误吗?
- 获取错误:在“(”标记之前进行预期的构造函数、析构函数或类型转换
- 显式调用类的析构函数时出现错误
- C++析构函数调用了错误的对象