Mic*_*x2a 9 c++ pointers scope vector
返回一个填充了局部变量的向量是否安全?
例如,如果我有......
#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`
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我Target
在for循环中创建多个实例,将它们推送到向量,并返回指向它的指针.因为Target
实例是在本地分配给堆栈的,这是否意味着返回的向量是不安全的,因为它引用了堆栈上的对象(可能很快会被覆盖等)?如果是这样,返回矢量的推荐方法是什么?
顺便说一下,我用C++写这个.
Kon*_*lph 19
当元素push_back
进入向量(或赋值给元素)时,元素会被复制.因此,您的代码是安全的 - 向量中的元素不是对局部变量的引用,它们由向量拥有.
此外,您甚至不需要返回指针(并且永远不会处理原始指针,而是使用智能指针).只需返回副本; 编译器足够聪明,可以对其进行优化,从而不会产生实际的冗余副本.
归档时间: |
|
查看次数: |
5701 次 |
最近记录: |