我有那个 C++ 代码
#include <iostream>
#include <vector>
#include <memory>
struct Foo{
int* a;
Foo(std::vector<int> vec)
{
a = &(vec.front());
}
};
struct Bar {
std::unique_ptr<int> a;
Bar(std::vector<int> vec)
{
a = std::make_unique<int>(vec.front());
}
};
int main() {
std::vector<int> vec = {42};
Foo foo(vec);
Bar bar(vec);
// returns 0, but should 42
std::cout << *foo.a << std::endl;
// but this returns 42
std::cout << *bar.a << std::endl;
return 0;
}
为什么 *foo.a 返回 0,而不是 42?我究竟做错了什么?
将线路更改Foo(std::vector<int> vec)
为Foo(std::vector<int>& vec)
,它会正常工作。看到它在这里工作。
问题是这vec
是一个局部变量,一旦函数调用返回它就不再有效。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句