【问题标题】:Premature end of execution due to a vector.push_back() [C++]由于 vector.push_back() [C++] 而提前结束执行
【发布时间】:2016-06-09 08:59:28
【问题描述】:

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

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

这是我的主要代码:

/*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;
}

这是附加到向量的对象的类:

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_ */

感谢大家的宝贵时间!

【问题讨论】:

  • 如果您说您对push_back 有疑问,如果您确实显示 有问题的代码(即您调用push_back 的代码),将会很有帮助。请尝试创建Minimal, Complete, and Verifiable Example 并展示给我们。
  • 您编辑的main 函数也不应该编译。 _vct 是一个指向对象的 pointer ,因此您需要使用例如_vct-&gt;push_back(...)。它也不能解决我的回答中提到的内存泄漏。最后,您是 Java 还是 C# 背景?在 C++ 中,您不需要使用 new 来创建对象,只需执行例如Commande cmd; 将创建一个 Commande 对象。
  • 谢谢大家,它现在正在工作。

标签: c++ vector crash push-back


【解决方案1】:

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

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

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

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

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

没有Minimal, Complete, and Verifiable Example,就不可能说别的。

【讨论】:

  • 因此,如何防止这种内存泄漏?
猜你喜欢
  • 2019-05-09
  • 1970-01-01
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-27
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多