prestokeys
prestokeys

Reputation: 4849

Returning by reference a member of a destroyed local variable

Can someone explain whether this is ok or not?

#include <iostream>
#include <vector>

struct A {
    std::vector<int> numbers;
    ~A() {std::cout << "A destroyed.\n";}
    const std::vector<int>& getNumbers() const {return numbers;}
    std::vector<int> getNumbersByValue() const {return numbers;}
};

std::vector<int> foo() {
    A a;
    a.numbers = {1,2,3,4,5};
//  return a.getNumbersByValue();  // This works of course.
    return a.getNumbers();  // Is this line wrong?
}

void useVector(std::vector<int>& v) {
    for (int i = 6; i <=10; i++)
    v.push_back(i);
}

int main() {
    auto v = foo();  // A destroyed.
    for (int x : v) std::cout << x << ' ';  // 1 2 3 4 5
    std::cout << '\n';

    useVector(v);
    for (int x : v) std::cout << x << ' ';  // 1 2 3 4 5 6 7 8 9 10
}

Since a is destroyed in foo(), then a.numbers is destroyed too, right? If foo() returns a copy of a.numbers, using A::getNumbersByValue(), then everything is fine. But above I'm using getNumbers(), which returns it by reference. The vector still survives after foo() ends. So I pass the vector into the function useVector to see if it still survives, and it does. So is everything ok here?

Upvotes: 0

Views: 73

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126203

Since foo returns its return value by value (not by reference), foo makes a copy of the vector to return. It copies from the reference it got back from getNumbers as part of the return before it destroys the local variable a, so at the time it makes the copy, the reference is still valid.

So this code is fine.

Upvotes: 3

Related Questions