Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding move semantics for std::array

I am trying to understand move semantics, so I did the following test:

#include <iostream>
#include <array>

using namespace std;

void tryToMove(array<double,3> && v) {
    array<double,3> v_ = std::move(v);
    std::cout << v_[0] << "  " << v_[1] << "  " << v_[2] <<'\n';
}

int main () {
    array<double,3> v{1,2,3};

    tryToMove(std::move(v));
    std::cout << v[0] << "  " << v[1] << "  " << v[2] <<'\n';
}

I was expecting a sementation fault in the std::cout of the main since v_ is supposed to be moved in tryToMove. However, the output is:

1 2 3
1 2 3

What is exactly happening here?

Thank you!

like image 382
Javi Avatar asked Dec 03 '22 17:12

Javi


2 Answers

I was expecting a sementation fault

First of all, most ways to get a segfault are as a result of undefined behaviour, in which case anything can happen and you probably shouldn't be expecting anything specific.

since v_ is supposed to be moved

A std::array contains its elements embedded directly inside it (not on the heap, referred to by a pointer, like a std::vector does) so you can't move its contents anywhere. They will always be inside it.

So all you've done is initialize a new array from the old one, you haven't moved anything. The elements of the new array will be initialized by rvalue doubles, but that doesn't move anything either, because you can't "move" a double (it has no externally-allocated data to transfer either). So it's just a copy of each element.

like image 125
Jonathan Wakely Avatar answered Dec 20 '22 09:12

Jonathan Wakely


The problem is that you expected a segmentation fault just because you accessed memory that is no longer yours.

Undefined behaviour means anything can happen.

In this instance, the state of v is unspecified, so your accesses to three elements of it may be valid or may not be. When they are valid (which they probably are because the underlying data is likely to be copied in this case) you're fine; when they are invalid, you cannot simply assume that the result will be a segmentation fault. A few things have to come together for the OS to raise a segmentation fault: it's not a magic bullet for detecting bugs.

like image 25
Lightness Races in Orbit Avatar answered Dec 20 '22 08:12

Lightness Races in Orbit