Wednesday 15 August 2012

c++ - const reference to a temporary object becomes broken after function scope (life time) -


By asking, I have a direct reference to a temporary object in C ++:

  Int main () {int a = 21; Int b = 21; // Error: Invalid initialization of non-conference reference // Inte & amp; Sum = a + b; E [...] // OK int corn & amp; Sum = a + b; Refund Amount; }   

But in the following example, const refers to a reference to a deleted floating object refnop . I wonder why?

  #include & lt; String & gt; # Include & lt; Map & gt; Struct A {// data std :: map & lt; Std :: string, std :: string & gt; Meter; // Functions Consultant A & A Nothing () const {return * this; } Zero init () {m ["aa"] = "bb"; } Bool Operator! = (A const & a) const {back a.m! = M; }}; Int main (A); A.init (); A const & amp; Ref = A (A); A const & amp; Refnop = A (A). nothing (); Int rate = 0; If (a! = Ref) rate + = 2; If (a! = Refnop) ret + = 4; Return writ; }   

Tested using GCC 4.1.2 and MSVC 2010, it returns 4 returns;

  $ & gt; G ++ -g refnop.cpp $ & gt; ./a.out; $ Echo? The difference between 4   

ref and ref is call for nothing () which in fact Nothing is there . After this call it seems, the temporary object is destroyed!

My question:
In the case of why refnop , the life time of the floating object is not the same as its const context?

The lifetime extension of a floating object should be done only once, when the temporary object is first Will be bound to reference. After that, the knowledge that has been referred to a floating object, so the expansion of further life is not possible.

A matter that bothers you

  a const & amp; Refnop = A (A). nothing ();   

This is similar to the case:

  A const & amp; Foo (a const and bar) {Return time; } // ... a const & amp; Broken = Fu (A ());   

In both cases, temporary function logic (for the this nothing () , bar foo () ) and the lifetime of the function logic expands its lifetime. I have 'extended' in the quote because the natural life of the temporary is already long, therefore there is no real extension.

Because the lifetime extension's property is non-transit, a reference (this is the view of the temporary object) will not extend the life of the temporary object, resulting in both the refnop and < Code> broken do not reference objects that no longer exist.

No comments:

Post a Comment