不能使用C ++中类头中定义的向量

时间:2014-04-17 07:56:15

标签: c++ qt vector push-back

我有一个路线类。在标题中,我定义了

private:
QVector<QPoint> cameraPoints;

在课程来源中,

void Route::SetCameraPositions(QVector<QPoint> *cam)
{
   QVector<QPoint> bla;
   QPoint t;
   int x,y;
   for(int i=0; i<cam->size(); i++) {
      x = cam->at(i).x();
      y = cam->at(i).y();
      t.setX(x);
      t.setY(y);
      bla.push_back(t) //Works
      cameraPoints.push_back(t); //Doesn't work
   }
}

我不能在头文件中定义push_back向量,但我可以在同一函数中定义的向量上使用push_back。我也试过std :: vector但是得到了同样的错误。

这是valgrind报告;

==3024==
==3024== Process terminating with default action of signal 11 (SIGSEGV)
==3024== General Protection Fault
==3024== at 0x410CA5: QBasicAtomicInt::operator!=(int) const (qbasicatomic.h:75)
==3024== by 0x417AEA: QVector<QPoint>::append(QPoint const&) (qvector.h:575)
==3024== by 0x4171C2: QVector<QPoint>::push_back(QPoint const&) (qvector.h:281)
==3024== by 0x420DF0: Route::SetCameraPositions(QVector<QPoint>*) (cRoute.cpp:46)
==3024== by 0x4107DA: MainWindow::SetCameraLocations() (mainwindow.cpp:678)
==3024== by 0x40C577: MainWindow::SetupModel() (mainwindow.cpp:141)
==3024== by 0x40B6CB: MainWindow::MainWindow(QWidget*) (mainwindow.cpp:48)
==3024== by 0x40B3BF: main (main.cpp:18)
==3024==
==3024== Events : Ir
==3024== Collected : 172003489
==3024==
==3024== I refs: 172,003,489
** Process crashed **

1 个答案:

答案 0 :(得分:1)

将我的评论转化为答案。

看起来您并未在有效SetCameraPositions()对象上调用Route。无法访问数据成员通常意味着无效的this指针。

在C ++中,最好创建具有​​自动存储持续时间的对象(&#34;在堆栈上#34;),因为这可以防止此类问题。就像这样:

Route r;
r.SetCameraPoints(whatever);

如果您需要对象的动态生命周期,则必须动态创建它,这意味着您必须先分配它。在现代C ++中,您将使用智能指针来管理对象的生命周期:

std::unique_ptr<Route> r(new Route());
r->SetCameraPoints(whatever);
// Once r goes out of scope, the Route object will be deallocated.

不推荐手动管理动态对象生存期(使用原始指针)。出于完整感,这里有你如何做到这一点,但是:

Route *r = new Route();
r->SetCameraPoints(whatever);

// once you want to deallocate the object:
delete r;