prolonging the lifetime of temporaries

前端 未结 4 508
太阳男子
太阳男子 2020-12-01 11:26

What is the design rationale behind allowing this

const Foo& a = function_returning_Foo_by_value();

but not this

Foo&am         


        
4条回答
  •  悲&欢浪女
    2020-12-01 11:57

    The reason that non-const pointers don't prolong the lifetime of temporaries is that non-const references can't be bound to temporaries in the first place.

    There are LOTS of reasons for that, I'll just show one classic example involving implicit widening conversions:

    struct Foo {};
    bool CreateFoo( Foo*& result ) { result = new Foo(); return true; }
    
    struct SpecialFoo : Foo {};
    SpecialFoo* p;
    if (CreateFoo(p)) { /* DUDE, WHERE'S MY OBJECT! */ }
    

    The rationale for allowing const references to bind temporaries is that it enables perfectly reasonable code like this:

    bool validate_the_cat(const string&);
    
    string thing[3];
    validate_the_cat(thing[1] + thing[2]);
    

    Note that no lifetime extension was needed in this case.

提交回复
热议问题