segmentation fault when moving std::vector

c++, c++11, g++, move-semantics

Solution

This function:

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

Returns a reference to a local object which is going to be destroyed when the call returns. Therefore, your program has Undefined Behavior. Therefore, the returned reference will be dangling by the time the move constructor of `data` is invoked here:

data d = randomize();

You should return a value of type `data`, and you shouldn't explicitly invoke `std::move()`:

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

This way, you will also give the compiler the opportunity to performed (Named) Return Value Optimization, possibly resulting in no call to the move constructor at all.

Problem

The following program crashes with segmention fault: ``` #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 with 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 std::vector move constructor, cause everything works fine without it. It looks like data object from randomize() is destroyed when function finishes, but shouldn't it rather be moved to the data object in main first?

Original source