2012年5月23日水曜日

C++を勉強中・・・ orz

std::shared_ptr使っているときにthisポインタを扱いたいときは
std::enable_shared_from_this<クラス名>を継承して,
shared_from_this()を使用して取得する・・・であっているのかな・・・.

  1. #include <iostream>  
  2. #include <memory>  
  3.   
  4. class Student : public std::enable_shared_from_this<Student>  
  5. {  
  6. public:  
  7.     Student(std::string name, int first_score, int second_score)  
  8.         : name_(name), first_score_(first_score),  
  9.           second_score_(second_score) {}  
  10.     ~Student() { std::cout << "delete " << name_ << std::endl; }  
  11.   
  12.     void printScore() {  
  13.         std::shared_ptr<Student> ptr = shared_from_this();  
  14.         std::cout << name_ << " : "  
  15.                   << first_score_ + second_score_ << std::endl;  
  16.     }  
  17.     std::shared_ptr<Student> getSharedPointer() {  
  18.         // これだとやばい・・・  
  19.         // return  std::shared_ptr<Student>(this);  
  20.         return  shared_from_this();  
  21.     }  
  22. private:  
  23.     std::string name_;  
  24.     int first_score_, second_score_;  
  25. };  
  26.   
  27. int main()  
  28. {  
  29.     auto student = std::make_shared<Student>("Miyanaga", 5200, 24000);  
  30.     auto it = student->getSharedPointer();  
  31.   
  32.     it->printScore();  
  33.     sleep(1);  
  34.   
  35.     return 0;  
  36. }  

0 件のコメント:

コメントを投稿