std::shared_ptrã§è¦ªåé¢ä¿ã«ããåã®ãã£ã¹ã.
ãã³ãã¬ã¼ãåãããã¯ã©ã¹ã¯ãã³ãã¬ã¼ããã©ã¡ã¼ã¿ã親åé¢ä¿ã§ãå¥ã¯ã©ã¹ãªã®ã§ä»£å ¥ã§ããããã¨ãæã£ã¦ããã§ããshared_ptrã§ãµã¤ã¼ã«ã§ãããããã£ã¹ãããæ¹æ³ããã£ã¦(´ã»âã»ï½)ï¾ï½° ã£ã¦æã£ãã®ã§ã¡ã¢ãã¦ãããªãã
#include <memory> #include <iostream> class Base { public: virtual void hello() { std::cout << "Hello in Base!" << std::endl; } }; class Sub : public Base { public: virtual void hello() override { std::cout << "Hello in Sub!" << std::endl; } }; int main(void) { std::shared_ptr<Base> p1 = std::make_shared<Base>(); std::shared_ptr<Sub> p2 = std::make_shared<Sub>(); std::shared_ptr<Base> p3 = std::make_shared<Sub>(); std::shared_ptr<Sub> p4 = std::dynamic_pointer_cast<Sub>(p3); p1->hello(); // => Hello in Base! p2->hello(); // => Hello in Sub! p3->hello(); // => Hello in Sub! p4->hello(); // => Hello in Sub! return 0;
ãªãã¡ã¬ã³ã¹è¦ãã dynamic_cast 以å¤ã®ãã£ã¹ããå ¨é¨å°ç¨ã®ãããã£ã½ãã
Specific functions:
shared_ptr - C++ Reference
make_shared Make shared_ptr (function template ) allocate_shared Allocate shared_ptr (function template ) static_pointer_cast Static cast of shared_ptr (function template ) dynamic_pointer_cast Dynamic cast of shared_ptr (function template ) const_pointer_cast Const cast of shared_ptr (function template ) get_deleter Get deleter from shared_ptr (function template )