shared_from_this called from constructor

前端 未结 7 1972
一生所求
一生所求 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
    {
        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 Create()
            {
                shared_ptr myClass = make_shared(false);
    
                //Use myClass or myClass.get() here, now that it is created.
    
                return myClass;
            }
    }
    
    //Somewhere.
    shared_ptr myClass = MyClass::Create();
    

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

提交回复
热议问题