Skip to content

Instantly share code, notes, and snippets.

@marcobergamin
Last active July 2, 2019 22:32
Show Gist options
  • Save marcobergamin/69e92857a47e4e2984da19459793ab56 to your computer and use it in GitHub Desktop.
Save marcobergamin/69e92857a47e4e2984da19459793ab56 to your computer and use it in GitHub Desktop.
std::enable_shared_from_this + factory method
#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