The following code results in SIGSEGV and I cannot understand why is that.
#include <iostream>
using namespace std;
struct C {
C(int x) { ptr = new int(x); }
C(C&& c) { ptr = c.ptr; c.ptr = nullptr; }
int* ptr;
};
void foo(int* x, C c) {
cout << *x << endl;
}
int main() {
C c(10);
foo(c.ptr, std::move(c));
return 0;
}
I would expect the pointer c.ptr to be passed by value to the function foo, however it behaves like its passed by reference.
Now, if I change the ordering of arguments: void foo(C c, int* x), than the problem disappears. The other solution is to create a local copy of c.ptr before calling to x, and than passing that local copy to foo.
I would like to understand why can't i pass c.ptr by value in the sample code above.