安全返回一个填充局部变量的向量? [英] Safe to return a vector populated with local variables?

查看:146
本文介绍了安全返回一个填充局部变量的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

返回一个已填充局部变量的向量是安全的吗?

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`
}

在这个例子中,我在一个for循环中创建多个 Target 实例,将它们推送到向量,并返回一个指针。因为 Target 实例被本地分配到堆栈,这意味着返回的向量是不安全的,因为它引用堆栈上的对象(可能很快被覆盖等) )?如果是这样,返回向量的推荐方法是什么?

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?

顺便说一下,我是用C ++编写的。

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

推荐答案

p>当 push_back 将它们复制到向量中(或分配给元素)时,元素被复制。因此,您的代码是安全的 - 向量中的元素不是对局部变量的引用,它们由向量所有。

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.

这篇关于安全返回一个填充局部变量的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆