C++ Language/Indirection/SmartPointers/ReturningThis

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Traditional C++ code might sometimes have wanted to do return this; (returning a CRType* raw pointer).

To instead return std::shared_ptr<CRType>, derive your class from std::enable_shared_from_type<CRType> (so that an internal std::shared_ptr<> will start owning this object), and return shared_from_this() instead of this.

Additional information about returning the this pointer as a smart pointer (includes interactive examples)