这是我在生产中运行的代码的缩小版。我发现,我的真实代码在gcc和英特尔编译器下表现不同,我最好的猜测是未定义的行为。请考虑以下示例代码:
#include <iostream>
struct baseFunctor{
virtual double operator()(double x) const = 0;
};
class mathObj{
const baseFunctor *tmp1, *tmp2;
public:
void set(const baseFunctor& b1, const baseFunctor& b2){
tmp1 = &b1;
tmp2 = &b2;
}
double getValue(double x){
return (tmp1->operator()(x) + tmp2->operator()(x));
}
};
int main () {
mathObj obj;
struct squareFunctor: public baseFunctor {
double operator()(double x) const { return x*x; }
};
struct cubeFunctor: public baseFunctor {
double operator()(double x) const { return x*x*x; }
};
obj.set(squareFunctor(), cubeFunctor());
std::cout << obj.getValue(10) << std::endl;
return 0;
}
obj.set(squareFunctor(), cubeFunctor());
可以调用未定义的行为吗?
答案 0 :(得分:5)
是的,它肯定是这样,因为您存储指向在语句末尾销毁的临时值的指针,然后使用它们。使用被破坏的对象是未定义的行为。
您需要单独创建值,然后使用它们调用set
:
cubeFunctor cf;
squareFunctor sf;
obj.set(sf, cf);
请注意,您无法通过按值存储仿函数来解决此问题(除非您使用模板),因为这会导致切片。
另外,作为附注,您可以更改getValue
来执行
return (*tmp1)(x) + (*tmp2)(x);
让它看起来更漂亮(你仍然可以获得动态调度)。