52 lines
1.3 KiB
Plaintext
52 lines
1.3 KiB
Plaintext
When you make an unqualified call to swap, argument dependent lookup will ensure that overloads will also be searched in the namespace where the types of the arguments of the call are declared.
|
||
|
||
|
||
However, argument dependent lookup won't happen if you explicitly qualify the call ``++std::swap++`` (as a reminder, overrides of ``++swap++`` should not be written in the standard namespace - see S3470) so the overload will not be found and the result of the swap may be different than expected.
|
||
|
||
|
||
If you want your code to work both with ``++std::swap++`` and with user-defined ``++swap++`` (for instance in a template), you should use a using declaration ``++using std::swap;++`` before calling ``++swap++`` without qualification.
|
||
|
||
|
||
== Noncompliant Code Example
|
||
|
||
----
|
||
namespace myCompany {
|
||
class A {/* ... */};
|
||
swap(A &a1, A &a2);
|
||
}
|
||
|
||
void f(myCompany::A &a1, myCompany::A &a2) {
|
||
// ...
|
||
std::swap(a1, a2); // Noncompliant
|
||
}
|
||
|
||
template<class T>
|
||
void g(T &t1, T &t2) {
|
||
// ...
|
||
std::swap(t1, t2); // Noncompliant, will not work correctly if T == myCompany::A
|
||
}
|
||
----
|
||
|
||
|
||
== Compliant Solution
|
||
|
||
----
|
||
namespace myCompany {
|
||
class A {/* ... */};
|
||
swap(A &a1, A &a2);
|
||
}
|
||
|
||
void f(myCompany::A &a1, myCompany::A &a2) {
|
||
// ...
|
||
swap(a1, a2);
|
||
}
|
||
|
||
template<class T>
|
||
void g(T &t1, T &t2) {
|
||
// ...
|
||
using std::swap;
|
||
swap(t1, t2);
|
||
}
|
||
----
|
||
|