Swap std :: vector as a function parameter

I would like to swap std::vector as a function parameter, so the vector does not need to be copied.

Something like that:

 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 any way to do this?

+4
source share
1 answer

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

 function(std::move(my_vector)); 

If this is not available to you, you can try something like this:

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

Let me know if you are lucky with this.

Or you can swap the vector directly for a couple after creating it:

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

Although, I think this will not help you if you need to return the value of std::make_pair as rvalue.

+3
source

Source: https://habr.com/ru/post/1395873/


All Articles