std::enable_shared_from_this<クラス名>を継承して,
shared_from_this()を使用して取得する・・・であっているのかな・・・.
- #include <iostream>
- #include <memory>
- class Student : public std::enable_shared_from_this<Student>
- {
- public:
- Student(std::string name, int first_score, int second_score)
- : name_(name), first_score_(first_score),
- second_score_(second_score) {}
- ~Student() { std::cout << "delete " << name_ << std::endl; }
- void printScore() {
- std::shared_ptr<Student> ptr = shared_from_this();
- std::cout << name_ << " : "
- << first_score_ + second_score_ << std::endl;
- }
- std::shared_ptr<Student> getSharedPointer() {
- // これだとやばい・・・
- // return std::shared_ptr<Student>(this);
- return shared_from_this();
- }
- private:
- std::string name_;
- int first_score_, second_score_;
- };
- int main()
- {
- auto student = std::make_shared<Student>("Miyanaga", 5200, 24000);
- auto it = student->getSharedPointer();
- it->printScore();
- sleep(1);
- return 0;
- }