const reference to temporary oddity

前端 未结 3 1432
情深已故
情深已故 2021-01-02 11:14

We all know that things like this are valid in c++:

const T &x = T();

while:

T &x = T();

is not.<

3条回答
  •  梦谈多话
    2021-01-02 11:23

    It prints 10 every time.

    Modify the main function a little and it won't print 10 anymore:

    int main()
    {
        B* p = f();
        cout << "C++\n";   // prints C++
        p->b();            // prints 4077568
    }
    

    how does this link gets established at what level?

    See 12.2 [class.temporary] §4 and §5:

    Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created.

    There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. The first context is [...]

    The second context is when a reference is bound to a temporary. 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 except: [...]

    A temporary bound to a reference parameter in a function call persists until the completion of the full-expression containing the call.

    So in your case, the temporary is destroyed after the evaluation of the full-expression new B(A(10)).

提交回复
热议问题