Segmentation error when moving std :: vector

The following program crashes with a segmentation error:

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

The code is compiled using g ++ version 4.7.2 (Debian 4.7.2-5):

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

What am I doing wrong? The problem seems to be in the std :: vector move constructor, because everything works fine without problems. It looks like the data object from randomize () is destroyed when the function ends, but shouldn't it be faster to transfer it to the data object in main?

+5
source share
2 answers

This function:

data&& randomize()
{
    // ...
    data d
    // ...
    return std::move(d);
}

, . Undefined . , data:

data d = randomize();

data, std::move():

data randomize()
{
    // ...
    data d
    // ...
    return d;
}

, () , .

+13

, :

data randomize()
{
    // ...
    data d
    // ...
    return std::move(d);
}

d.

0

All Articles