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

前端 未结 6 1842
太阳男子
太阳男子 2021-01-13 09:32

I\'ve tried to code like this several times:

struct Foo
{
    double const& f;
    Foo(double const& fx) : f(fx)
    {
        printf(\"%f %f\\n\", f         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-13 09:49

    If the temporary variable exists at the point where the reference is used, then the behaviour is well defined.

    If the temporary ceases to exist before the reference is used, then the behaviour of using the reference is undefined.

    Unfortunately, your code is an example of the latter. The temporary which holds the result of 123.0 + 2.0 ceases to exist when the statement Foo p(123.0 + 2.0) finishes. The next statement printf("%f\n", p.GetF()) then accesses a reference to that temporary which no longer exists.

    Generally speaking, undefined behaviour is considered unsafe - it means there is no requirement on what the code actually does. The result you are seeing in testing is not guaranteed.

提交回复
热议问题