The following code leads to SIGSEGV, and I do not understand why this is.
#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 c.ptr pointer to be passed by the value of the foo function, however it behaves like passed by reference.
Now, if I change the order of the arguments: void foo (C c, int * x), then the problem disappears. Another solution is to create a local copy of c.ptr before calling x, and then pass that local copy to foo.
I would like to understand why I cannot pass c.ptr by value in the above code example.
Buyuk source
share