【发布时间】:2011-06-15 22:11:35
【问题描述】:
我一直在研究我的程序,我决定使用g++ -O3 开启一些优化。突然,我的程序开始出现段错误。我已经找到了有问题的代码,并将我的程序最小化为仍然存在段错误的东西(仅在使用 3 级优化时)。我希望有人可以快速浏览一下代码(我尽量将其最小化):
// src/main.cpp
#include "rt/lights/point.hpp"
int main(int argc, char **argv)
{
rt::Light *light = new rt::light::Point(alg::vector(.0f, 5.0f, 5.0f), rt::Color(1.0f), .5f);
return 0;
}
// include/rt/lights/point.hpp
#ifndef RT_LIGHT_POINT_HPP_
#define RT_LIGHT_POINT_HPP_
#include "rt/accelerator.hpp"
#include "rt/color.hpp"
#include "rt/intersection.hpp"
#include "rt/light.hpp" // abstract
namespace rt {
namespace light {
class Point : public Light
{
public:
Point(alg::vector pos, Color color, float intensity) : Light(intensity * color), pos(pos) {}
Color get_contrib(const Intersection&, const Accelerator&, const alg::vector& toViewer) const;
private:
alg::vector pos;
};
} // namespace light
} // namespace rt
#endif
// include/rt/light.hpp
#ifndef RT_LIGHT_HPP_
#define RT_LIGHT_HPP_
#include "algebra/vector.hpp"
#include "rt/color.hpp"
namespace rt {
class Intersection;
class Accelerator;
class Light
{
public:
Light(Color intensity) : intensity(intensity) {}
virtual Color get_contrib(const Intersection&, const Accelerator&, const alg::vector& toViewer) const = 0;
Color get_intensity() const {return intensity;}
protected:
Color intensity;
};
} // namespace rt
#endif
我想了解一下为什么这段代码只会在使用优化时出现段错误,以及如何阻止它这样做。谢谢!
$ find src/ -name "*.cpp" | xargs g++ -I include/ -O3
$ ./a.out
Segmentation fault
编辑:根据要求,alg::vector 的构造函数
结构向量 { 浮动 x, y, z; 矢量():x(.0f),y(.0f),z(.0f){} 显式向量(float f):x(f),y(f),z(f){} 矢量(浮动 x,浮动 y,浮动 z):x(x),y(y),z(z){} // ...Edit2:使用 -g 编译时添加 gdb 输出
Edit3:rt::Color 的来源。
// 包含/rt/color.hpp #ifndef RT_COLOR_HPP_ #define RT_COLOR_HPP_ #include "代数/向量.hpp" 命名空间 rt { /************************************************* ****************************** * 类定义 */ 结构颜色 { 浮动r,g,b; 颜色():r(.0f),g(.0f),b(.0f){} 显式颜色(float f):r(f),g(f),b(f){} 颜色(float r, float g, float b) : r(r), g(g), b(b) {} 颜色& 运算符+= (const 颜色&); 颜色&运算符*= (const Color&); 颜色& 运算符*= (float); }; /************************************************* ****************************** * 会员运营商 */ 内联颜色和颜色::operator+= (const Color& other) { r += 其他.r; g += 其他.g; b += 其他.b; 返回*这个; } 内联颜色和颜色::operator*= (const Color& other) { r *= 其他.r; g *= 其他.g; b *= 其他.b; 返回*这个; } 内联颜色和颜色::operator*= (float f) { r *= f; g *= f; b *= f; } /************************************************* ****************************** * 其他运算符 */ 内联颜色运算符+(颜色 lhs,const Color& rhs) { 返回 lhs += rhs; } 内联颜色运算符*(颜色 lhs、const Color& rhs) { 返回 lhs *= rhs; } 内联颜色运算符*(颜色 c,浮点 f) { 返回 c *= f; } 内联颜色运算符* (float f, Color c) { 返回 c *= f; } } // 命名空间 rt #万一【问题讨论】:
-
您是否尝试过使用 -g 进行编译以查看回溯是否完全可用?
-
你能把
alg::vector的拷贝构造函数贴出来吗? -
operator*()看起来如何用于将Color与强度相乘? -
我也会用
-Wall -Wextra编译代码。如果您收到警告,它们可能包含问题的线索。 -
@chrisaycock,GCC 可以将多个源编译成一个 a.out,所以这里不是问题。也请求颜色的来源。
标签: c++ optimization g++ segmentation-fault