1
class A{};

void use(const A&){}

unique_ptr<A> my_fun(){
    return make_unique<A>();
}

int main(){
    const A& rA = *my_fun();    //Error: object will be destructed
    use(rA);

    const auto rA1 = my_fun();    //make a copy of the unique_ptr. transfer the ownership
    use(*rA1);

    const auto& rA2 = my_fun();    
    use(*rA2);

    return 0;
}

rA doesn't work because the returning pointer will be destructed. rA1 works fine, because the transferring of the ownership preserves the object. My question is about rA2. It's an alias of the returning unique_ptr, right? Why the object is not destroyed, like in the case of rA?

Milo Lu
  • 3,176
  • 3
  • 35
  • 46
  • 1
    Possible duplicate of [Does a const reference prolong the life of a temporary?](http://stackoverflow.com/questions/2784262/does-a-const-reference-prolong-the-life-of-a-temporary) – LogicStuff Feb 07 '16 at 01:00

0 Answers0