代码之家  ›  专栏  ›  技术社区  ›  Kumar Roshan Mehta

线程中的简单函数调用

  •  0
  • Kumar Roshan Mehta  · 技术社区  · 6 年前
    class base 
    { 
    public: 
        virtual void fun_1() { cout << "base-1\n"; } 
        virtual void fun_2() { cout << "base-2\n"; } 
    
    }; 
    
    class derived : public base 
    { 
    public: 
        void fun_1() { cout << "derived-1\n"; } 
        void fun_2() { cout << "derived-2\n"; 
        } 
    }; 
    
    
    class caller
    {
        private:
            derived d;
            unique_ptr<base> b = make_unique<derived>(d);
    
        public:
            void me()
            {
                b->fun_2(); //? How to do this in thread
                // std::thread t(std::bind(&base::fun_2, b), this);
                // t.join();
            }
    };
    
    int main() 
    {  
        caller c;    
        c.me();
        return 0;
    }
    

    我写了一个小程序来学习智能指针和虚拟函数。现在我被卡住了,我怎么能叫b->在线程中,我不能更改基类和派生类。我还必须使用unique_ptr,不能更改为shared_ptr。如果可能的话,请在取消注释我注释的行时解释错误消息。

    1 回复  |  直到 6 年前
        1
  •  1
  •   snake_style    6 年前

    void me()
    {
        std::thread t(&base::fun_2, std::move(b));
        t.join();
    }
    

    您的错误消息是由于试图创建不允许的唯一\u ptr副本而导致的。如果你真的需要这种类型的电话 绑定 )像这样使用它:

    std::thread t(std::bind(&base::fun_2, std::ref(b)));
    

    std::thread t(std::bind(&base::fun_2, b.get()));