Skip to content

Instantly share code, notes, and snippets.

@slwu89
Last active December 14, 2017 17:15
Show Gist options
  • Save slwu89/270d51bf6dd8ba98ff6e12385065b5cc to your computer and use it in GitHub Desktop.
Save slwu89/270d51bf6dd8ba98ff6e12385065b5cc to your computer and use it in GitHub Desktop.
more detailed version of object suicide
#include <iostream>
#include <memory>
#include <utility>
#include <string>
#include <vector>
class human;
typedef std::unique_ptr<human> human_ptr;
typedef std::vector<human_ptr> human_vector;
class house {
public:
house(const int& _houseID) : houseID(_houseID) {
std::cout << "house " << houseID << " being born at " << this << std::endl;
};
~house(){
std::cout << "house " << houseID << " being killed at " << this << std::endl;
};
void add_human(human_ptr h){
humans.push_back(std::move(h));
};
human_vector& get_humans(){ return humans; };
private:
int houseID;
human_vector humans;
};
class human {
public:
/* constructor */
human(std::string _x, house* _h): x(_x), h(_h) {
std::cout << "human " << x << " being born at " << this << std::endl;
};
/* destructor */
~human(){
std::cout << "human " << x << " being killed at " << this << std::endl;
};
/* suicide */
void suicide(){
std::cout << "human " << x << " suiciding at " << this << std::endl;
for(auto it = h->get_humans().begin(); it != h->get_humans().end(); it++){
if(it->get() == this){
std::cout << "i found myself!" << std::endl;
h->get_humans().erase(it);
}
}
};
void hi(){
std::cout << "human " << x << " says hi " << std::endl;
};
/* print out human */
friend std::ostream& operator<<(std::ostream& os, human& h) {
return os << "human " << h.x << " says hi" << std::endl;
}
private:
std::string x;
house* h;
};
int main(){
house aHouse(1);
human_ptr bob = std::make_unique<human>("bob",&aHouse);
human_ptr alice = std::make_unique<human>("alice",&aHouse);
aHouse.add_human(std::move(bob));
aHouse.add_human(std::move(alice));
aHouse.add_human(std::make_unique<human>("carol",&aHouse));
std::cout << "there are " << aHouse.get_humans().size() << " humans in the house" << std::endl;
aHouse.get_humans().front()->suicide();
std::cout << "there are " << aHouse.get_humans().size() << " humans in the house" << std::endl;
std::unique_ptr<house> house2 = std::make_unique<house>(2);
human_ptr grace = std::make_unique<human>("grace",house2.get());
house2->add_human(std::move(grace));
for(auto &h : house2->get_humans()){
h->hi();
};
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment