Is it possible to put "using std :: swap"? in the title?

I read that when you swap change things in C ++, you should always using std::swap; , then call swap unqualified, so it automatically selects std:: for std:: and built-in types, your custom for custom types and template std:: for everything else.

So, can I just put using std::swap; in the header that contains each file and no need to worry about it?

I understand that avoiding using in the header is common practice. However, is there a problem in this particular case?

+7
c ++ namespaces argument-dependent-lookup
source share
2 answers

The swap hint is using std::swap in the largest possible local area. Surely, one in the header file, which is widely included, does not meet this requirement. It still pollutes the global namespace in unexpected ways (someone does not expect std::swap be imported into the global namespace) and should be avoided just like using namespace .

+7
source share

The fundamental problem here is that you assume that people do not write their own swap , which are the best matches, which do subtle or completely different things for the semantics of std::swap and related friends. For a simple example, consider

 void swap(int* a, int* b); 

where the contents of the pointers are replaced. Now try swapping the int* pair. You might think that the pointers change places, but instead be surprised! this is the content that is being replaced.

Indeed, the manual for swap is the same as any other, only using in the maximum possible local area and not earlier and definitely not in the header.

0
source share

All Articles