Based on pp. 8
Free Functions
template<typename T> void swap(scoped_ptr<T>& a,scoped_ptr<T>& b)This function offers the preferred means by which to exchange the
contents of two scoped pointers. It is preferable because
swap(scoped1,scoped2) can be applied generically (in templated code)
to many pointer types, including raw pointers and third-party smart
pointers.[2] scoped1.swap(scoped2) only works on smart pointers, not
on raw pointers, and only on those that define the operation.
int* pA = new int(10);
int *pB = new int(20);
boost::swap(pA, pB); // Error: could not deduce template argument for 'boost::scoped_ptr<T> &' from 'int *'
Question> How to swap raw pointers with boost::swap?
I don’t understand why the other answers are telling you not to use
boost::swap. The entire purpose ofboost::swapis to hide theusing std::swap; swap(x, y);business. This works just fine:Obviously if you haven’t included
boost/swap.hppthis won’t work. That’s how you useboost::swapto swap two things. You should always prefer to swap two things in this form!What you’re reading is simply stating that
boost::scoped_ptralso provides an overload ofswapinside theboostnamespace, so that this works too:But it should be clear that this won’t work:
Because
boost/scoped_ptr.hpphas not provided (and indeed doesn’t have the responsibility to provide) a general implementation ofboost::swap. If you want to useboost::swapin general, you must includeboost/swap.hpp:Like that. If you have Boost available to do, do not fall back to the using
std::swapstuff.