C++ using this pointer in constructors

后端 未结 8 1119
时光取名叫无心
时光取名叫无心 2020-12-15 16:45

In C++, during a class constructor, I started a new thread with this pointer as a parameter which will be used in the thread extensively (say, call

8条回答
  •  难免孤独
    2020-12-15 17:25

    Basically, what you need is two-phase construction: You want to start your thread only after the object is fully constructed. John Dibling answered a similar (not a duplicate) question yesterday exhaustively discussing two-phase construction. You might want to have a look at it.

    Note, however, that this still leaves the problem that the thread might be started before a derived class' constructor is done. (Derived classes' constructors are called after those of their base classes.)

    So in the end the safest thing is probably to manually start the thread:

    class Thread { 
      public: 
        Thread();
        virtual ~Thread();
        void start();
        // ...
    };
    
    class MyThread : public Thread { 
      public:
        MyThread() : Thread() {}
        // ... 
    };
    
    void f()
    {
      MyThread thrd;
      thrd.start();
      // ...
    }
    

提交回复
热议问题