Reputation: 13
I know that sounds silly but I am not quite sure about this because our teacher told us that we should swap element like that
int a=3, b=1, tmp;
tmp=a;
a=b;
b=tmp
and not like that
int a=3, b=1;
swap(a,b);
Could you tell me what's bad about using the function swap
for swapping variables
Upvotes: 0
Views: 91
Reputation: 20396
One of three scenarios is true.
std::swap
is literally identical to the example code your teacher provided, because the canonical implementation of std::swap
is just A temp = std::move(a); a = std::move(b); b = std::move(temp);
std::swap
is better code than the example code your teacher provided because some objects can optimize swaps without needing to move the whole object 3 times.std::swap
is worse because, since the std::
prefix wasn't specified, there's a chance the call to swap
is picking up an ADL'd version of the function that is some horrific code that doesn't actually do what it claims to do. (ex: void swap(A & a, A & b) {a.val += 15;}
)Scenario 3 is theoretically possible, but extremely unlikely. If your teacher hasn't expressly suggested that that is what's happening, then it's probably not a scenario worth considering. So we're left to deduce what the teacher intends based on the first two scenarios.
In those situations, since std::swap
is basically always going to be better or exactly as good, my only conclusion is that your teacher either expects a scenario where std::swap
will be inaccessible to you, or else is simply trying to explicitly teach you how to implement swap
yourself.
Or possibly your teacher is bad at their job. Assume the former explanations first, though.
Upvotes: 4
Reputation: 10939
There is nothing bad about std::swap
, in fact the first approach to swapping can even be wrong in certain cases. For example std::unique_ptr
has a deleted copy-constructor, so you cannot copy it to a temporary and back. The std::swap
function on the other hand works just fine.
#include <memory>
struct A {};
int main()
{
auto a = std::make_unique<A>();
auto b = std::make_unique<A>();
// Does not work!
// Copy constructor is deleted.
std::unique_ptr<A> tmp;
tmp = a;
a = b;
b = tmp;
// Works just fine.
std::swap(a,b);
}
Upvotes: 1