Why passing std :: move (object) and a member of this object to a function calls SIGSEGV

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.

+4
source share
2 answers

It is passed by value, however:

foo(c.ptr, std::move(c));

, , .

++ ( -...) .

"Unspecified" , . . , std::move. , , null. c.ptr, now-null .

+6

foo(c.ptr, std::move(c));, , c.ptr std::move(c). . , std::move(c) , c.ptr nullptr. cout << *x << endl, *x, x - nullptr.

+3

Source: https://habr.com/ru/post/1690856/


All Articles