1

我有这些类SphereTriangle它们都是Intersectable. Intersectable有一个公共成员变量colour。考虑以下代码片段:

float t_min = 100000.0f;
pair<float, f3Vector> point_hit;
Intersectable * object_hit;
Triangle triangle;
Sphere sphere_trans;
bool hit = false;

//loop through triangles
for(unsigned int i = 0; i < mesh->tvi.size(); i++){
    ...

    triangle = Triangle((fRGB)mesh->color[mesh->tci[i].c0], va.toVector3(), vb.toVector3(), vc.toVector3());
    point_hit = triangle.intersect(orig, dir, c_near, c_far);

    if(point_hit.first != 0.0f && point_hit.first < t_min){
        object_hit = &triangle;
        std::cout << "color1 " << object_hit->color << std::endl;
hit = true;
        ...
    }
}

// loop through spheres
for(unsigned int j = 0; j < spheres.size(); j++){
    ...

    sphere_trans = Sphere(sphere.color, center3, sphere.getRadius());
    point_hit = sphere_trans.intersect(orig, dir, c_near, c_far);

    if(point_hit.first != 0 && point_hit.first < t_min){
        object_hit = &sphere_trans;
        std::cout << "color1 " << object_hit->color << std::endl;
hit = true;
        ...
    }
}

if(hit){
    std::cout << "color2 " << object_hit->color << std::endl;
}

我期待如果我有一个输出,color1 (1 0 0)并且下一个输出是一个输出color2 (...)颜色的值应该是相同的。但是,这不会发生。事实上,我总是得到相同的输出color2 (...)。你能告诉我我做错了什么吗?谢谢!

4

2 回答 2

2

在本声明中:

object_hit = &sphere_trans;

您正在分配object_hit给本地(到 for 循环)变量的地址。一旦你离开for循环,这pointer将不再有效并且取消引用pointer是未定义的行为。

于 2013-05-15T19:47:53.227 回答
2

让我们瘦一点...

Intersectable * object_hit;
Sphere sphere_trans;

// loop through spheres
for(unsigned int j = 0; j < spheres.size(); j++)
{
    ...  
    sphere_trans = Sphere(sphere.color, center3, sphere.getRadius());

    if(some condition)
    {
        object_hit = &sphere_trans;
        ...    
    }
}

现在,当满足条件时,object_hit指向sphere_trans。但是下一次循环时,sphere_trans会分配一个新对象。所以,当然,object_hit现在也指向新对象,这可能不是您想要的。

最好的办法是做object_hit一个对象而不是一个指针。或者只是将索引保存到数组中。

于 2013-05-15T21:05:22.037 回答