Created
January 13, 2012 16:00
-
-
Save mloskot/1607156 to your computer and use it in GitHub Desktop.
Moveable semantic fun
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <utility> | |
#include <boost/noncopyable.hpp> | |
struct animal : private boost::noncopyable | |
{ | |
animal() {} | |
animal(char const* name) : name(name) {} | |
animal(animal&& a) : name(a.name) | |
{ | |
a.name.clear(); | |
} | |
animal& operator=(animal&& a) | |
{ | |
name = a.name; | |
a.name.clear(); | |
return *this; | |
} | |
std::string name; | |
}; | |
struct cat : public animal | |
{ | |
cat(char const* name) : animal(name) {} | |
}; | |
struct dog : public animal | |
{ | |
dog(char const* name) : animal(name) {} | |
}; | |
struct Cage | |
{ | |
private: | |
animal animal_; | |
public: | |
void set_animal(animal&& a) | |
{ | |
animal_ = std::move(a); | |
} | |
std::string who() const { return animal_.name; } | |
}; | |
int main() | |
{ | |
using std::cout; | |
using std::endl; | |
Cage cage; | |
cage.set_animal(cat("Kitty")); | |
std::cout << cage.who() << std::endl; | |
cage.set_animal(dog("Bamboozle")); | |
std::cout << cage.who() << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment