I am trying to compose an illustrative example which shows how to implement move semantics on an object that will be stored in a vector
.
Please consider the following code, which is my illustrative example so far. It is designed to be a canonical, pedantically correct implementation of an object that implements move semantics, does not implement copy semantics, and can be stored in a vector<>
(Where T is Moveable, below). How did I do?
#include <string>
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <memory>
#include <iterator>
using namespace std;
class Moveable
{
public:
string foo_;
string bar_;
Moveable(Moveable&& rhs) : foo_(std::move(rhs.foo_)), bar_(std::move(rhs.bar_)) {} // move construction
Moveable(const string& foo) : foo_(foo) {}; // convert construction
Moveable& operator=(Moveable&& rhs) // move assignment
{
foo_ = std::move(rhs.foo_);
bar_ = std::move(rhs.bar_);
return * this;
}
private:
Moveable(const Moveable&); // not defined, not copy-constructible
Moveable& operator=(const Moveable&); // not defined, not copy-assignable
Moveable(); // not defined, not default constructible
};
Moveable generate_it()
{
static string foo ;
if( foo.empty() || foo[0] == 'z' )
foo.insert(0, 1, 'a');
else
foo[0]++;
return foo;
}
int main()
{
typedef vector<Moveable> Moveables;
Moveables v;
generate_n(back_inserter(v), 1024, &generate_it);
cout << v.size() << endl;
string target = "zzz";
auto that = find_if(v.begin(), v.end(), [target](const Moveables::value_type& it) -> bool
{
return it.foo_ == target;
});
if( that != v.end() )
v.erase(that);
sort(v.begin(), v.end(), [](const Moveables::value_type& lhs, const Moveables::value_type& rhs) -> bool
{
return lhs.foo_ > rhs.foo_;
});
cout << v.size() << endl;
}
unique_ptr
which ultimately was orthogonal to what I was really going for. \$\endgroup\$