由于 vector.push_back() [C++] 导致执行过早结束

Premature end of execution due to a vector.push_back() [C++]

大家早上好, 我目前的代码有问题,它崩溃时没有任何错误输出。 我希望你能帮我一把!

当我在向量中附加元素时出现问题,但不是在第一次迭代时总是在第二次迭代时出现。

这是我的主要代码:

/*Various includes*/
int main(void)
{
  int cmpt = 0;
  std::vector<Commande> _vct;
  Commande cmd;
  while(cmpt < 15)
  {
    cout << "..." << endl;
    _vct.push_back(cmd);
    cout <<" test cmd" << _vct[cmpt].getBytes() << endl;
    cmpt++;

    }

  return 0;
}

这是附加到矢量的对象的 class:

Commande::Commande()
{
    bytes="";
    from="";
    type="";
    first_s="";
    last_s="";
    value=-1;
    first_i=-1;
    last_i=-1;
}

Commande::~Commande()
{

}

void Commande::toString()
{
    cout << "=-_-=> from: '" << (this)->getFrom() << "', type: '" << (this)->getType() << "', value: '" << (this)->getValue() << "', bytes: '" << (this)->getBytes() << "'." << endl;
}

void Commande::fromStringToInteger()
{
    (this)->setFirst_i(atoi((this)->getFirst().c_str()));
    (this)->setLast_i(atoi((this)->getLast().c_str()));
}

最后 Commande.cpp 的 .h:

#include <cstdlib>
#include <iostream>

#ifndef COMMANDE_H_
#define COMMANDE_H_

using namespace std;

class Commande
{
    public:
    Commande();
    virtual ~Commande();
    /*Various geters ans seters*/
    void toString(void);
    void fromStringToInteger();

    private:
    string bytes, from, type, first_s, last_s;
    int value, first_i, last_i;
};

#endif /* COMMANDE_H_ */

谢谢大家的宝贵时间!

与你问的问题无关,但还有很多其他问题...

例如,让我们仔细看看这些行(摘自您的 main 函数):

while(...)
{
    Commande* cmd = new Commande();
    (this)->appendCmdList(*cmd);
}

首先它不应该编译。非成员函数中没有this,只有非静态成员函数中有

然后你有内存泄漏,因为你动态分配了一个新的 Commande 实例,但是你将 实例 (而不是指针)传递给 appendCmdList 函数,这意味着下一次循环迭代时指针丢失(因为它超出范围)并且您分配一个新指针而不删除以前的对象或保存指针。

没有Minimal, Complete, and Verifiable Example就没法说别的了。