【问题标题】:Boost Scoped Pointer To Boost Thread提升作用域指针以提升线程
【发布时间】:2013-08-28 16:32:05
【问题描述】:

今天我想使用 boost::scoped_ptr 来指向 boost::thread。

在我的 Thread.h 中有boost::scoped_ptr<boost::thread> m_thread,在我的 Thread.cpp 中有一个函数 create(),应该在其中创建 boost::thread。 我试过Thread::m_thread (new boost::thread(attr, boost::bind(%Thread::run, this)));,但不出所料,它不起作用。

我无法弄清楚自己(或通过使用 boost 文档)我将如何做到这一点,因为我不完全了解 scoped_ptr 发生了什么以及它是如何工作的。 在我使用原始指针之前,它工作得很好,但我现在不允许使用它。

感谢您的宝贵时间!

【问题讨论】:

    标签: c++ boost boost-smart-ptr


    【解决方案1】:

    不知道你遇到了什么错误,试试这个:

    class Thread {
     public:
      Thread() : thread_(new boost::thread(boost::bind(&Thread::run, this))) {
      }
    
      void run() {
      }
    
      ~Thread() {
        thread_->join();
      }
    
     private:
      boost::scoped_ptr<boost::thread> thread_;
    };
    
    int main() {
      Thread thread;
    }
    

    但不要忘记,该线程可能在构造函数结束其工作之前开始。

    【讨论】:

    • 如果我没有遗漏什么,这几乎就是我尝试过的以及我的问题中所说的内容。 ;) 我的错误是关于 m_thread 的定义,它说:error C2064: term does not evaluate to a functiontaking 1 arguments 那是关于Thread::m_thread(new boost::thread(attr, boost::bind(&amp;Thread::run, this)));
    • 嘿,m_thread 在 Thread.h 中声明并在 Thread.cpp 中的 create() 函数中调用。但是,问题(很可能)是在创建线程对象后,m_thread 已经在内部定义了默认值,因此无法在create() 函数中被覆盖。我在create() 中创建另一个名为tmp 的scoped_ptr 并将我的boost::thread 分配给它,然后将其与m_thread 交换并在完成create() 后自动销毁它。可能不是最美丽的事情,但对我有用。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-10-20
    • 2015-09-01
    • 2011-06-08
    • 2017-01-16
    • 1970-01-01
    • 2011-02-01
    • 2011-01-24
    • 1970-01-01
    相关资源
    最近更新 更多