user350954
user350954

Reputation: 329

why std::swap does not work with address operator?

Why using std::swap() in C++ I cannot swap addresses?
For example, with the following

int x = 1, y = 2; 
std::swap(&x, &y);

I got compile error:

error: no matching function for call to 'swap(int*, int*)'

But if I do the following:

int *px = &x, *py = &y;
std::swap(px, py);

It works fine. So there is a swap(int*, int*)!

Any idea what's wrong for the first version? Thanks in advance.

Upvotes: 1

Views: 996

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490158

std::swap takes its parameters by (lvalue) reference. Therefore, what you pass must be lvalues. In addition, the types referred to by the parameters must be MoveConstructible and MoveAssignable (so not all lvalues will necessarily work either--for example, attempting to swap two string literals is likely to fail).

Upvotes: 8

Related Questions