I don't understand why the other answers are telling you not to use boost::swap
. The entire purpose of boost::swap
is to hide the using std::swap; swap(x, y);
business. This works just fine:
#include <boost/swap.hpp>
int main()
{
int* pA = new int(10);
int *pB = new int(20);
boost::swap(pA, pB);
delete pA;
delete pB;
}
Obviously if you haven't included boost/swap.hpp
this won't work. That's how you use boost::swap
to swap two things. You should always prefer to swap two things in this form!
What you're reading is simply stating that boost::scoped_ptr
also provides an overload of swap
inside the boost
namespace, so that this works too:
#include <boost/scoped_ptr.hpp>
int main()
{
boost::scoped_ptr<int> pA(new int(20));
boost::scoped_ptr<int> pB(new int(20));
boost::swap(pA, pB);
}
But it should be clear that this won't work:
#include <boost/scoped_ptr.hpp>
int main()
{
int* pA = new int(10);
int *pB = new int(20);
boost::swap(pA, pB);
delete pA;
delete pB;
}
Because boost/scoped_ptr.hpp
has not provided (and indeed doesn't have the responsibility to provide) a general implementation of boost::swap
. If you want to use boost::swap
in general, you must include boost/swap.hpp
:
#include <boost/scoped_ptr.hpp>
#include <boost/swap.hpp>
int main()
{
int* pA = new int(10);
int *pB = new int(20);
boost::scoped_ptr<int> pC(new int(20));
boost::scoped_ptr<int> pD(new int(20));
boost::swap(pA, pB);
boost::swap(pC, pD);
delete pA;
delete pB;
}
Like that. If you have Boost available to do, do not fall back to the using std::swap
stuff.