shared_from_this called from constructor

前端 未结 7 1966
一生所求
一生所求 2021-02-03 21:31

I have to register an object in a container upon its creation. Without smart pointers I\'d use something like this:

a_class::a_class()
{
    register_somewhere(t         


        
相关标签:
7条回答
  • 2021-02-03 22:30

    Here's my solution:

    class MyClass: enable_shared_from_this<MyClass>
    {
        public:
            //If you use this, you will die.
            MyClass(bool areYouBeingAnIdiot = true)
            {
                if (areYouBeingAnIdiot)
                {
                    throw exception("Don't call this constructor! Use the Create function!");
                }
    
                //Can't/Don't use this or shared_from_this() here.
            }
    
            static shared_ptr<MyClass> Create()
            {
                shared_ptr<MyClass> myClass = make_shared<MyClass>(false);
    
                //Use myClass or myClass.get() here, now that it is created.
    
                return myClass;
            }
    }
    
    //Somewhere.
    shared_ptr<MyClass> myClass = MyClass::Create();
    

    (The constructor has to be public to be callable from a static member function, even an internal one...)

    0 讨论(0)
提交回复
热议问题