A
A
Arthur2017-09-18 10:38:12
C++ / C#
Arthur, 2017-09-18 10:38:12

What is the lifetime of the variable?

std::forward_list <T> copy_list(const std::forward_list<T>& in)
{
    auto out = in;
    out.reverse();
    return out;
}

As far as I understand, the out variable, including what it refers to, should be destroyed and it should not be possible to use this reference and data outside of it. it's all on the stack. But, the value returned by it is printed and can be easily manipulated. Why?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evgeny Shatunov, 2017-09-18
@Carver182

auto out = in;
The type of the `out` variable will be `std::forward_list<T>`. [Explanation 1] , [Explanation 2]
So `out ` will be a local variable and will have a local lifetime.
The only exception is temporary lifetime extension . Then the lifetime of the variable will be extended.

The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details.

M
Maria Maltseva, 2017-09-18
@Moriam

On the stack, a place is separately reserved for the value returned by the function, and it is there, and not at the address of the out variable, that the result is written through return. And, accordingly, further work occurs precisely at the address with the returned value.

Z
zencd, 2017-09-18
@zencd

A variable and its value are two different things. The variable has a limited lifetime, scope. The value can be used further because the value will be copied, the copy constructor will be called. Optimizations are possible, but the essence is this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question