下面的程序崩溃,并segmention故障:段故障时的std ::矢量
#include <iostream>
#include <vector>
using namespace std;
struct data
{
data() : a(random()), b(random()), v({random(), random(), random()}) {}
data(data&& m) noexcept : a(m.a), b(m.b), v(std::move(m.v)) { }
long int a;
long int b;
std::vector<long int> v;
};
data&& randomize()
{
srandom(time(0));
data d;
d.a = random();
return std::move(d);
}
int main(int argc, char** argv)
{
data d = randomize();
cout << d.a << " " << d.b << endl;
return 0;
}
的代码被编译以克++版本4.7.2(Debian的4.7.2-5):
g++ -std=c++11 -g test.cpp
我做错了什么?这个问题似乎是在std :: vector移动构造函数,导致一切正常工作没有它。看起来来自randomize()的数据对象在函数完成时会被销毁,但不应该将它移动到主数据对象中吗?
请注意,这里不需要返回* rvalue *引用(即使它有效返回对本地自动变量的引用)。如果可能的话,函数返回值总是被移动。 –