简体   繁体   中英

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM