Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A wrapper to allow moving of values into a C++ 11 lambda
template<typename T>
class MoveCapture {
mutable T m_value;
public:
MoveCapture( ) = delete;
MoveCapture( T && val ) : m_value( std::move( val ) ) { }
MoveCapture( MoveCapture const & other ) : m_value( std::move( other.m_value ) ) { }
MoveCapture& operator=(MoveCapture const & rhs) {
if( this != &rhs ) {
m_value = std::move( rhs.m_value );
}
return *this;
}
T& value( ) {
return m_value;
}
T const & value( ) const {
return m_value;
}
T& operator*() {
return m_value.operator*();
}
T const & operator*() const {
return m_value.operator*();
}
T const * operator->() const {
return m_value.operator->();
}
~MoveCapture( ) = default;
T move_out( ) {
auto result = std::move( m_value );
return result;
}
}; // class MoveCapture
template<typename T>
MoveCapture<T> as_move_only( T&& val ) {
return MoveCapture<T>( std::move( val ) );
}
////////////////////////////////
/// Example usage
int main( int, char** ) {
auto lots_of_data = std::vector<LargeObj>( 100000000 );
auto mlots_of_data = as_move_only( std::move( lots_of_data ) );
auto processed_data = [mlots_of_data](...) {
// do something
return mlots_of_data;
}( );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment