返回填充有局部变量的向量是否安全?
返回一个充满局部变量的向量是否安全?
例如,如果我有...
#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
实例是在本地分配到堆栈的,这是否意味着返回的向量不安全,因为它引用堆栈上的对象(可能很快就会被覆盖等)?如果是这样,返回向量的推荐方法是什么?
顺便说一下,我是用 C++ 写的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您将元素
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.