4

I would like to swap in an std::vector as a function parameter, so that the vector doesn't have to be copied.

Something like this:

function( std::vector< MyType >().swap( my_vector ) );

Or in my case like this:

std::make_pair( 0, std::vector< MyType >().swap( my_vector ) );

But of course std::vector::swap returns void, not the created vector.

Is there a way to do this?

3
  • 2
    why don't you use a reference?
    – perreal
    Feb 11, 2012 at 5:08
  • @perreal Because I don't have control over the function. (std::make_pair)
    – user542687
    Feb 11, 2012 at 5:10
  • @Jay: If the function copies its argument, and you can't change the function, it is impossible to make the function not copy its argument. (Of course, in the case of std::make_pair, there is a version which takes its parameters by rvalue reference and which forwards them to the pair constructor, thus moving the argument rather than copying it (if the argument is an rvalue reference))
    – Mankarse
    Feb 11, 2012 at 5:12

1 Answer 1

3

Use any modern compiler, then you can use std::move, which takes your vector and returns it as an rvalue:

function(std::move(my_vector));

If that's not available to you, you could try something like this:

template<typename T>
T Move(T & val)
{
    T ret;
    ret.swap(val);
    return ret;
}

Let me know if you have any luck with that.

Or, you can swap the vector directly into the pair after its creation:

std::pair<int, std::vector<MyType> > p;
p.second.swap(my_vector);

Though, I guess this won't help you if you need the return value of std::make_pair as an rvalue.

1
  • I had trouble setting up C++11x in my environment, so I wasn't able to test std::move, but I am sure it would work well. Thanks.
    – user542687
    Feb 16, 2012 at 23:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.