c++ - vector 删除调用了错误的析构函数

标签 c++

我有一个带有一些对象的 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/

相关文章:

c++ - 在书中的示例代码 "introduction to 3d game programming with directx 11"

c++ - 获取异常类型

c++ - 将 "zero"值设置为成员变量

c++ - map<string, int>中,是否保证int初始化为0?

c++ - 一个 obj2(A tmp) ; C++中的这个语句是什么意思

c++ - 使用 C++ 正则表达式一次性替换多个正则表达式

C++ 哈希链接函数

我的类中的 C++ 运行时错误

c++ - 在 C++ 2 中读取二进制文件

c++ - 文件在多个程序中持续无法打开