不能在 C++ 中使用类标头中定义的向量
Can't use vector defined in class header in C++
我有一个路由类。在标题中,我定义了
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;
相关文章:
- 自己的自定义向量类. 内存重新分配
- C++类中的类作为自定义向量(如何初始化?
- 在C++中使用带有自定义向量的迭代器
- 创建自定义向量类错误
- 如何在<typename> <long> 不更改给定代码的情况下将自定义向量与 STL 向量相互转换?
- 如何为我的自定义向量类实现类似 vector.insert 的方法
- 如何在没有参数列表的情况下定义向量无效使用模板名称 std::vector
- 将 boost odeint 与 std::map 和自定义向量空间代数一起使用时,没有可行的重载'='
- Push_back类定义向量的函数
- 自定义向量类的解构函数
- c++在单独的函数中定义向量
- 定义向量元素的破坏顺序是否合理
- vector.erase 和 std::remove 在自定义向量上
- 在自定义类中定义向量
- C++11 initializer_list构造函数,带有自定义向量类的头和cpp文件
- 如何在<ifstream> C++ 类中定义向量
- 为自定义向量类中的特定元素指定一个值.作为a[5]=3 C++
- 重载自定义向量类中的和运算符
- 如何在C++中定义向量<boost::mutex>?
- 在自定义向量类中调用了错误的构造函数