回答編集履歴

1

update

2016/10/11 03:01

投稿

yohhoy
yohhoy

スコア6191

test CHANGED
@@ -1,4 +1,4 @@
1
- thisポインタから`shared_ptr`型(や`std::weak_ptr`型)を取り出す場合は、[`std::enable_shared_from_this`クラステンプレート](http://cpprefjp.github.io/reference/memory/enable_shared_from_this.html)を利用してください。同クラスから[CRTP](https://ja.wikibooks.org/wiki/More_C%2B%2B_Idioms/%E5%A5%87%E5%A6%99%E3%81%AB%E5%86%8D%E5%B8%B0%E3%81%97%E3%81%9F%E3%83%86%E3%83%B3%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3(Curiously_Recurring_Template_Pattern))の形でpublic継承し、`shared_from_this()`メンバ関数を呼び出します。
1
+ thisポインタから`std::shared_ptr`型(や`std::weak_ptr`型)を取り出す場合は、[`std::enable_shared_from_this`クラステンプレート](http://cpprefjp.github.io/reference/memory/enable_shared_from_this.html)を利用してください。同クラスから[CRTP](https://ja.wikibooks.org/wiki/More_C%2B%2B_Idioms/%E5%A5%87%E5%A6%99%E3%81%AB%E5%86%8D%E5%B8%B0%E3%81%97%E3%81%9F%E3%83%86%E3%83%B3%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3(Curiously_Recurring_Template_Pattern))の形でpublic継承し、`shared_from_this()`メンバ関数を呼び出します。
2
2
 
3
3
 
4
4
 
@@ -57,3 +57,7 @@
57
57
  }
58
58
 
59
59
  ```
60
+
61
+
62
+
63
+ なお`shared_ptr<Container>(this);`として強引に`shared_ptr`型を生成するのはNGです。型変換によりコンパイラはごまかせますが、この`shared_ptr`オブジェクトのスコープが切れたときに意図せずデストラクタ`~Container()`を呼び出し、thisオブジェクトが破壊されてしまいます。