Is it safe to make a const reference member to a temporary variable?

Viewed 3535

I've tried to code like this several times:

struct Foo
{
    double const& f;
    Foo(double const& fx) : f(fx)
    {
        printf("%f %f\n", fx, this->f); // 125 125
    }

    double GetF() const
    {
        return f;
    }
};
int main()
{
    Foo p(123.0 + 2.0);
    printf("%f\n", p.GetF()); // 0
    return 0;
}

But it doesn't crash at all. I've also used valgrind to test the program but no error or warning occured. So, I assume that the compiler automatically generated a code directing the reference to another hidden variable. But I'm really not sure.

7 Answers

If the temporary variable exists at the point where the reference is used, then the behavior is well defined. And in this case this temporary variable exists exactly because it is referenced! Form C++11 standard section 12.2.5:

The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference ...

Yes, the word hidden by '...' is the "except" and multiple exceptions are listed there, but none of them are applicable in this example case. So this is legal and well defined, should produce no warnings, but not very widely known corner case.

As others say it is currently unsafe. So it should be compile-time checked. So when one stores the reference one should also forbid rvalues:

    Foo(double &&)=delete;
Related