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

Can't use vector defined in class header in C++

本文关键字:定义 向量 C++ 不能      更新时间:2023-10-16

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

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

将我的评论转化为答案

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

在C++中,最好创建具有自动存储持续时间("在堆栈上")的对象,因为这样可以防止此类问题。简单地说:

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;