[英]why does vector return miss some value?
int main(int argc, char argv)
{
int myarray[] = {1, 2, 3, 5};
std::vector<int> array(myarray, myarray + 4);
std::vector<int> *p = testvector(array);
std::vector<int>::const_iterator it;
for(it=p->begin(); it != p->end(); ++ it)
{
printf("%d ", *it);
}
return 0;
}
std::vector<int> *testvector(std::vector<int> array)
{
return &array;
}
Above is my test code; 以上是我的测试代码; what is wrong that it returned 0 0 3 5 instead of 1 2 3 5
有什么不对,它返回0 0 3 5而不是1 2 3 5
Look at std::vector<int> *testvector(std::vector<int> array)
carefully. 仔细查看
std::vector<int> *testvector(std::vector<int> array)
。 This is taking a deep copy of the input parameter array
. 这是输入参数
array
的深层副本 。
The returned pointer will be dangling once array
is out of scope. 一旦
array
超出范围,返回的指针将悬空 。 The behaviour on dereferencing that pointer will be undefined . 取消引用该指针的行为将是未定义的 。 That's why your program is behaving oddly.
这就是你的程序表现奇怪的原因。
Interestingly, if you had written std::vector<int>& array
as the parameter (ie passed by reference ) then this would have worked, since you would be returning a pointer to the vector defined in main
! 有趣的是,如果您已经将
std::vector<int>& array
作为参数编写(即通过引用传递),那么这将有效,因为您将返回指向main
定义的向量的指针! This code would be extremely brittle though. 这段代码虽然非常脆弱。
this: 这个:
std::vector<int> *testvector(std::vector<int> array)
should be replaced with: 应替换为:
std::vector<int> *testvector(std::vector<int>& array)
However, this is not a real solution since there is no point from your example. 但是,这不是一个真正的解决方案,因为您的示例没有意义。 I think you have an X problem and you are just posting the Y one.
我认为你有一个X问题,而你只是张贴了Y问题。 if you post your real problem, it will be easier to help you.
如果你发布真正的问题,它会更容易帮助你。
Change 更改
std::vector<int> *testvector(std::vector<int> array)
to 至
std::vector<int> *testvector(std::vector<int>& array) // Note the &
Otherwise the array is copied to a local variable, which is destroyed at the end of testvector()
which invalidates the returned pointer. 否则,该数组将复制到一个局部变量,该变量在
testvector()
结束时被销毁,这会使返回的指针无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.