将对象的实例作为函数参数传递 - 此代码是否调用未定义的行为?

Gra*_*Guy 3 c++ pass-by-reference undefined-behavior

这是我在生产中运行的代码的缩小版本.我发现,我的真实代码在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;
}
Run Code Online (Sandbox Code Playgroud)

可以obj.set(squareFunctor(), cubeFunctor());调用未定义的行为吗?

Set*_*gie 5

是肯定的,因为您存储指向在语句结尾处销毁的临时值的指针,然后使用它们.使用被破坏的对象是未定义的行为.

您需要单独创建值,然后set使用它们调用:

cubeFunctor cf;
squareFunctor sf;

obj.set(sf, cf);
Run Code Online (Sandbox Code Playgroud)

请注意,您无法通过按值存储仿函数来解决此问题(除非您使用模板),因为这会导致切片.

另外作为旁注,您可以getValue改为做

return (*tmp1)(x) + (*tmp2)(x);
Run Code Online (Sandbox Code Playgroud)

让它看起来更漂亮(你仍然可以获得动态调度).