覆盖未调用的虚函数

时间:2014-11-27 02:51:11

标签: c++

我有一个具有多个虚函数的结构对象

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

1 个答案:

答案 0 :(得分:3)

不要使用malloc来构造非POD对象。请改用new

所有malloc都是分配字节 - 它构造对象。您的sphere对象具有虚函数,派生自基类等。这些类型必须正确构造,而malloc不能完成这项工作。

此外,如果您拨打free(),则还必须将其更改为致电delete

在对象构建方面使用malloc的唯一时间是,如果您正在使用代码未执行的placement-new