Skip to content

Instantly share code, notes, and snippets.

@beached
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beached/31802bfcbc61a37b8bd4 to your computer and use it in GitHub Desktop.
Save beached/31802bfcbc61a37b8bd4 to your computer and use it in GitHub Desktop.
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