Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use boost::swap to swap raw pointers?

Tags:

c++

boost

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?

like image 500
q0987 Avatar asked Feb 15 '26 16:02

q0987


1 Answers

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.

like image 101
GManNickG Avatar answered Feb 18 '26 08:02

GManNickG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!