0

I know that I can use "Lifetime Extension Reference Binding" to keep a temporary around for the duration of the local scope const auto& temp = "lorem ipsum"s but I was curious if there was a way to force the duration beyond the local scope without converting it to a permenant object.

More explicitly, I'm wondering if I could do: const auto& temp = foo();

Attempt 1:

const string& foo() {
    const auto& temp = "lorem ipsum"s;
    return temp;
}

Attempt 2:

struct bar {
    const string& temp;
};

const bar foo() {
    const auto& temp = "lorem ipsum"s;
    const bar result = {temp};
    return result;
}

Is there a way that I haven't thought of which will let me get temp outside the local scope without converting it to a permanent object?

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • 1
    @NathanOliver attempt 1 never works either. Note the return type. – T.C. Jun 06 '16 at 12:03
  • 1
    No. Just imagine if it were possible - how on earth would the compiler keep track of the object and know when to destroy it through all the references you are copying? Keep a reference count with every temporary? – T.C. Jun 06 '16 at 12:04
  • @T.C. Ah yes. For some reason I though he was returning by value. – NathanOliver Jun 06 '16 at 12:05
  • @NathanOliver I had just learned about "Lifetime Extension by Reference Binding" and I wanted to know if I could actually further extend the temporary. As far a practical purpose, I'm just trying to understand the concept. I don't think this is a duplicate? I'm wondering if there is a way to get a reference to a temporary outside the scope it was declared in. – Jonathan Mee Jun 06 '16 at 12:11
  • @T.C. Yeah I knew neither of them would work. Sounds like you're saying there isn't a way to do this. Which is the answer that I'm looking for. – Jonathan Mee Jun 06 '16 at 12:12
  • 1
    Hopefully, the standard reference quoted in the [accepted answer](http://stackoverflow.com/a/2784304/514235) is answering this Q. – iammilind Jun 06 '16 at 12:25
  • @iammilind Yeah that exactly answered the question good call on the duplicate. – Jonathan Mee Jun 06 '16 at 12:30

0 Answers0