Last active
July 2, 2019 22:32
-
-
Save marcobergamin/69e92857a47e4e2984da19459793ab56 to your computer and use it in GitHub Desktop.
std::enable_shared_from_this + factory method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <memory> | |
using namespace std; | |
class Widget : public std::enable_shared_from_this<Widget> | |
{ | |
public: | |
template<typename... Ts> | |
static std::shared_ptr<Widget> Create(Ts&&... params) | |
{ | |
return std::shared_ptr<Widget>( | |
new Widget(std::forward<Ts>(params)...)); | |
} | |
std::shared_ptr<Widget> GetSharedPtr() | |
{ | |
return shared_from_this(); | |
} | |
private: | |
// Set the ctor private to make the creation possible only through Create | |
// static method | |
Widget(int x, double y) | |
{ | |
_x = x; | |
_y = y; | |
} | |
int _x; | |
double _y; | |
}; | |
int main() | |
{ | |
auto wid {Widget::Create(10, 5.0)}; | |
auto widSptr {wid->GetSharedPtr()}; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment