gpt4 book ai didi

c++ - move std::vector 时出现段错误

转载 作者:可可西里 更新时间:2023-11-01 18:17:27 26 4
gpt4 key购买 nike

<分区>

以下程序因段错误而崩溃:

#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;
}

代码使用 g++ 版本 4.7.2 (Debian 4.7.2-5) 编译:

g++ -std=c++11 -g test.cpp

我做错了什么?问题似乎出在 std::vector move 构造函数中,导致没有它一切正常。看起来 randomize() 中的数据对象在函数完成时被销毁了,但它不应该首先 move 到 main 中的数据对象吗?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com