// $ g++ --std=c++11 -Wall -Wextra focemove.cpp
// $ ./a.out
// Yes using rvalue, move semantics
// Yes using rvalue, move semantics
// Oh no you forgot std::move somewhere. Deep copy occurs
//
// After delete unwanted ctor
// focemove.cpp: In function ‘void helper(std::vector< int >&&)’:
// focemove.cpp:44:20: error: use of deleted function ‘TestClass::TestClass(std::vector< int >&)’
// focemove.cpp:28:3: error: declared here
//
// testet with 4.7.4 - 5.2.1
#include < vector >
#include < iostream >
#include < utility >
using namespace std;
// this class store biiiig data in a std::vector.
// If we initialize it with a const reference ctor a deep copy occurs.
// To prevent this, either dont proice a const reference ctor or better:
// forbid it at all.
class TestClass {
public:
TestClass(vector< int > & other)
: vec(other)
{
cout << "Oh no you forgot std::move somewhere. Deep copy occurs\n";
}
// do we have to delete a const and non-const version here??
// TestClass(const vector< int > & other) = delete;
// TestClass(vector< int > & other) = delete;
TestClass(vector< int > && other)
: vec(other)
{
cout << "Yes using rvalue, move semantics\n";
}
private:
vector< int > vec;
};
void helper(vector< in t> && other) {
// is other a rvalue or lvalue? It depends on the caller
// here we forgot to use std::move(other)
// other is a named rvalue and thus no move semantics are used
TestClass a(other);
// comment in this to test after fix TestClass constructor
// TestClass a(move(other));
}
int main() {
// this works all fine. All use move semantics
TestClass(vector< int >()); // using temporaries, unnamed variables
vector< int > other;
TestClass(std::move(other)); // named variable other is converted to an unnamed with std::move
// this call is okay
helper(std::move(other));
// this line triggers a error
// cannot bind ‘std::vector< int >’ lvalue to ‘std::vector< int >&&’
// helper(other);
return 0;
}
30.09.2015
c++11 move semantics - force it
Comments Off on c++11 move semantics - force it
No Comments
No comments yet.
RSS feed for comments on this post.
Sorry, the comment form is closed at this time.