Swap crashes in case of int and works in case of string

#include <iostream> #include <string> #include <algorithm> int main() { std::string str1 = "good", str2 = "luck"; swap(str1,str2); /*Line A*/ int x = 5, y= 3; swap(x,y); /*Line B*/ } 

If I comment on line B, the code compiles (http://www.ideone.com/hbHwf), while commenting on line A, the code does not compile (http://www.ideone.com/odHka), and I get the following error :

 error: 'swap' was not declared in this scope 

Why won't I get errors in the first case?

+4
source share
4 answers

swap(str1, str2) works due to argument dependent search

PS: ADL Traps

+7
source

You do not qualify swap ; it works when passing std::string objects due to ADL , but since int not in the std , you should fully qualify call:

 std::swap(x, y); 

or use the using declaration:

 using std::swap; swap(x, y); 
+3
source
Lines

are in the std :: namespace, so the compiler is looking for swap () for strings. ints are not, therefore not. Do you want to:

 std::swap(x,y); 
+2
source

In both cases, you should use std::swap() instead of swap() .

+1
source

All Articles