1

我刚刚为游戏服务器创建了线程池,但在编译我不知道如何修复的内容时遇到了一个错误。

错误 :

Connection/CConnection.cpp:在 lambda 函数中:Connection/CConnection.cpp:62:6:错误:没有为这个 lambda 函数捕获“this”

线程池声明:

class Worker {
public:
    Worker(ThreadPool &s) : pool(s) { }
    void operator()();
private:
    ThreadPool &pool; 
};

// the actual thread pool
class ThreadPool {
public:
    ThreadPool(size_t);
    template<class F>
    void enqueue(F f);
    ~ThreadPool();
private:
    // need to keep track of threads so we can join them
    std::vector< std::unique_ptr<boost::thread> > workers;

    // the io_service we are wrapping
    boost::asio::io_service service;
    boost::asio::io_service::work working;
    friend class Worker;
};

template<class F>
void ThreadPool::enqueue(F f)
{
    service.post(f);
}

使用它的功能:

void CConnection::handle()
{
     int i = 0;
     ThreadPool pool(4);
     pool.enqueue([i]
    {
     char * databuffer;
     databuffer = new char[16];
     for(int i = 0;i<16;i++)
     {
      databuffer[i] = 0x00;
     }
     databuffer[0] = 16;
     databuffer[4] = 1;
     databuffer[8] = 1;
     databuffer[12] = 1;
     asynchronousSend(databuffer, 16);
    });
}

有人能告诉我在哪里,有什么问题吗?

4

1 回答 1

2

我的猜测是这asynchronousSendCConnection类中的一个函数。要在对象中调用函数,您必须捕获this

pool.enqueue([this] { ... });

如您所见,我已经删除了i不需要的捕获,因为您i在 lambda 中声明了一个本地。

于 2013-06-02T09:47:56.230 回答