Is it possible to change a temporary object and pass it as an argument?

Is it possible to change a temporary object and pass it as an argument?

struct Foo {    
   Foo& ref() { return *this; }
   Foo& operator--() { /*do something*/; return *this; }
   // another members
};
Foo getfoo() { return Foo(); } // return Foo() for example or something else
void func_val(Foo x) {}
void func_ref(const Foo & x) {}

int main() {
   func_val(--getfoo());     // #1 OK?
   func_ref(getfoo());       // #2 OK?
   func_ref(getfoo().ref()); // #3 OK?
   // the following line is a real example 
   //    using --vector.end() instead of --getfoo()
   func_ref(--getfoo());     // #4 OK? 

   const Foo & xref = --getfoo(); //  Does const extend the lifetime ?
   func_ref(xref);     // #5 OK? 
   func_val(xref);     // #6 OK? 

}

It is known that assigning a temporary object to refer to a constant increases the lifetime of this temporary object. What about lines 4 and 5 of my code? Is it true that the x reference is always valid in the func_ref function? The fact is that the operator - returns some link, and the compiler does not see any relationship between this link and the temporary one we created.

+3
source share
2 answers
func_val(--getfoo());     // #1 OK?

, . operator-- - -, ( lvalue ). func_val. , , , getfoo(), .

func_ref(getfoo());       // #2 OK?

, . getfoo() , const. , . , func_ref ( ).

func_ref(getfoo().ref());

, . , const , lvalue, .

// the following line is a real example 
//    using --vector.end() instead of --getfoo()

. , vector.end() a T* (). non-class, .

func_ref(--getfoo()); 

, . #1, lvalue , const . #3 ( ).

const Foo & xref = --getfoo();

. , , , . --getfoo() l, , . , (, , , ).

, , getfoo() xref, xref .

, , .

( xref, . , ( , , , ), ).

+3

full, . , func_val(--getfoo()); , getfoo(), . , func_val().

+4

Source: https://habr.com/ru/post/1720172/


All Articles