Sign in to follow this  
Nitage

[C++] Advice on custom swap function pls

Recommended Posts

Nitage    1107
I've come up with a small swap function for use in generic code. It's based on the standard adl swap trick, but it's designed to be used in situations where you only really need to assign, but you want to be able to take advantage of specialized swap functions where they exists. For example, swapping two vectors is much faster than assigning one to the other, and is equivilent if you don't care about the end value of the right parameter. Does anyone have any comments/constructive criticisms?
namespace detail
{
    //called swap even though it assigns - ugly but necessary
    template< class T >
    void swap(T& left, T& right)
    {
        left = right;
    }
}

//Uses ADL to pick out any specialized swap algorithms, defaulting to the assigning 'swap'
template< class T >
void swap_or_assign(T& left, T& right)
{
    using detail::swap;
    swap(left,right);
}


Share this post


Link to post
Share on other sites
ToohrVyk    1595
The name is confusing, in my opinion (EDIT: maybe something like "transfer" would be more adapted). Also, wouldn't the use of a pointer or reference accomplish the same thing without assignments and/or swaps?

Share this post


Link to post
Share on other sites
Nitage    1107
The original purpose of it was to be used to remove items from a vector in which ordering wasn't important using the technique the last element is copied over the one to be erased, then pop_back is called.

I realised that it would probably be quicker to swap objects that provided a custom swap function, but three times as slow and require a temporary variable in the case where no custom swap existed. - this is my attempt to automatically choose the best way at compile time.

It has some problems (like any class declared in namespace std will still use the generic std::swap algorithm and there's no guarentee that a custom swap will be faster than a single assignment) but I think it could be useful.

I like the name 'transfer' much better than 'swap_or_assign' as well.

Thanks for the comments.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this