Last active
December 12, 2017 20:04
-
-
Save slwu89/2be80b3d12a4bc5aa30cfdb4783c1792 to your computer and use it in GitHub Desktop.
logical way to do object suicide with pointers, also an example of move semantics
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 <memory.h> | |
#include <utility> | |
#include <vector> | |
class human; | |
typedef std::unique_ptr<human> human_ptr; | |
typedef std::vector<human_ptr> humans_obj; | |
class human { | |
public: | |
/* constructor */ | |
human(int _x, humans_obj* _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->begin(); it != h->end(); it++){ | |
if(it->get() == this){ | |
std::cout << "i found myself!" << std::endl; | |
h->erase(it); | |
} | |
}; | |
}; | |
/* print out human */ | |
friend std::ostream& operator<<(std::ostream& os, human& h) { | |
return os << "human " << h.x << " says hi" << std::endl; | |
} | |
private: | |
int x; | |
humans_obj* h; | |
}; | |
int main(){ | |
humans_obj house1; | |
humans_obj house2; | |
for(int i=1; i<4; i++){ | |
house1.push_back(std::make_unique<human>(i,&house1)); | |
} | |
for(auto &h : house1){ | |
std::cout << *h; | |
}; | |
std::cout << "size of house1 " << house1.size() << std::endl; | |
house1[0]->suicide(); | |
std::cout << "size of house1 " << house1.size() << std::endl; | |
std::cout << "who is in house1 " << std::endl; | |
for(auto &h : house1){ | |
std::cout << *h; | |
}; | |
std::cout << "moving house" << std::endl; | |
house2.push_back(std::move(house1[0])); | |
house1.erase(house1.begin()); | |
std::cout << "size of house1 " << house1.size() << std::endl; | |
std::cout << "size of house2 " << house2.size() << std::endl; | |
std::cout << "who is in house1 " << std::endl; | |
for(auto &h : house1){ | |
std::cout << *h; | |
}; | |
std::cout << "who is in house2 " << 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
may need a custom move constructor or something to update the
humans_obj* h
within the person when they move house?