Skip to content

Instantly share code, notes, and snippets.

@slwu89
Created January 5, 2018 00:30
Show Gist options
  • Save slwu89/382c16aaf533a8b434e1142214214d33 to your computer and use it in GitHub Desktop.
Save slwu89/382c16aaf533a8b434e1142214214d33 to your computer and use it in GitHub Desktop.
move some unique_ptr between containers
// human.hpp
#ifndef human_hpp
#define human_hpp
#include <stdio.h>
#include <string>
#include <iostream>
class human {
public:
/* constructor & destructor */
human(const std::string& _name);
~human();
/* copy constructor and assignment */
human(const human& h) = delete;
human& operator=(const human& h) = delete;
/* move constructor & assignment */
human(human&& h);
human& operator=(human&& h);
/* accessors */
std::string& get_name();
/* print out human */
friend std::ostream& operator<<(std::ostream& os, human& h) {
return os << "human " << h.name << " says hi" << std::endl;
}
private:
std::string name;
};
#endif /* human_hpp */
// human.cpp
#include "human.hpp"
/* constructor & destructor */
human::human(const std::string& _name) : name(_name) {
std::cout << "human " << name << " being born at " << this << std::endl;
};
human::~human(){
std::cout << "human " << name << " being killed at " << this << std::endl;
};
/* move constructor & assignment */
human::human(human&& h) = default;
human& human::operator=(human&& h) = default;
/* accessors */
std::string& human::get_name(){return name;};
// main.cpp
#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
#include "human.hpp"
using human_ptr = std::unique_ptr<human>;
using house = std::vector<human_ptr>;
int main() {
house house1;
house1.push_back(std::make_unique<human>("alice"));
house1.push_back(std::make_unique<human>("bob"));
house1.push_back(std::make_unique<human>("carol"));
std::cout << "house1 has " << house1.size() << " humans" << std::endl;
for(auto &h : house1){
std::cout << *h;
}
house house2;
std::string nameToMove("alice");
auto it = std::find_if(house1.begin(),house1.end(),[nameToMove](const human_ptr& h){
return nameToMove.compare(h->get_name())==0;
});
if(it!=house1.end()){
std::cout << "found alice" << std::endl;
}
house2.push_back(std::move(*it));
house1.erase(it);
std::cout << "house1 has " << house1.size() << " humans" << std::endl;
std::cout << "house2 has " << house2.size() << " humans" << std::endl;
for(auto &h : house2){
std::cout << *h;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment