我有一个具有多个虚函数的结构对象
object.h
struct object {
public:
...
virtual float intersect(Point, Vector, object*, Point*);
virtual Vector normal(Point, object*);
};
它们在另一个名为sphere
的结构中实现sphere.h
struct sphere: public object {
...
// intersect ray with sphere
float intersect(Point, Vector, object*, Point*) override;
// return the unit normal at a point on sphere
Vector normal(Point, object*) override;
};
我通过
创建并存储指向矢量中球体的指针extern vector<object*> scene;
sphere *new_sphere;
new_sphere = (sphere *) malloc(sizeof(sphere));
...
scene.push_back(new_sphere);
因此,当我尝试使用以下代码调用时,会出现问题
extern std::vector<object*> scene;
...
object *intersect_scene(Point p, Vector u, Point *intersect, int ignore) {
for (vector<object*>::iterator it = scene.begin(); it != scene.end(); ++it) {
float intersect_point = (*it)->intersect(p, u, *it, &temp_hit);
}
我从gdb
收到以下错误Program received signal SIGSEGV, Segmentation fault.
0x00000000004042ef in intersect_scene (p=..., u=..., intersect=0x7fffffffdcd0,
ignore=-1) at trace.cpp:70
70 float intersect_point = (*it)->intersect(p, u, *it, &temp_hit);
有人可以给我一些关于这里发生了什么的见解吗?
按要求:
struct Point{
float x;
float y;
float z;
};
struct Vector{
float x;
float y;
float z;
};
答案 0 :(得分:3)
不要使用malloc
来构造非POD对象。请改用new
。
所有malloc
都是分配字节 - 它不构造对象。您的sphere
对象具有虚函数,派生自基类等。这些类型必须正确构造,而malloc不能完成这项工作。
此外,如果您拨打free()
,则还必须将其更改为致电delete
。
在对象构建方面使用malloc
的唯一时间是,如果您正在使用代码未执行的placement-new
。