Safe to return a vector populated with local varia

2020-06-03 09:30发布

问题:

Is it safe to return a vector that's been filled with local variables?

For example, if I have...

#include <vector>

struct Target
{
public:
    int Var1;
    // ... snip ...
    int Var20;
};


class Test
{
public:
    std::vector<Target> *Run(void)
    {
        std::vector<Target> *targets = new std::vector<Target>;
        for(int i=0; i<5; i++) {
            Target t = Target();
            t.Var1 = i;
            // ... snip ...
            t.Var20 = i*2; // Or some other number.
            targets->push_back(t);
        }
        return targets;
    }


};

int main()
{
    Test t = Test();
    std::vector<Target> *container = t.Run();

    // Do stuff with `container`
}

In this example, I'm creating multiple Target instances in a for loop, pushing them to the vector, and returning a pointer to it. Because the Target instances were allocated locally, to the stack, does that mean that the returned vector is unsafe because it's referring to objects on the stack (that may soon be overwritten, etc)? If so, what's the recommended way to return a vector?

I'm writing this in C++, by the way.

回答1:

Elements get copied when you push_back them into a vector (or assign to elements). Your code is therefore safe – the elements in the vector are no references to local variables, they are owned by the vector.

Furthermore, you don’t even need to return a pointer (and never handle raw pointers, use smart pointers instead). Just return a copy instead; the compiler is smart enough to optimise this so that no actual redundant copy is made.