C++ - Boost.Promise、Boost.Unique_Future和移动语义

3

我正在按照Bartosz Milewski在这里的一些教程进行学习,我觉得非常有用。 然而,作者使用了C++11线程标准的 just::thread 实现(我目前还没有),因此我决定暂时采用boost线程,因为教程的作者说这很容易做到。这在系列的前三个教程中似乎是成立的,但是我在第四个教程中遇到了一些问题。以下是我的代码:

#include <iostream>
#include <cassert>
#include <boost\thread.hpp>
#include <boost\thread\future.hpp>

void thFun(boost::promise<std::string> & prms)
{
    std::string str("Hi from future!");
    prms.set_value(str);
}

int main()
{
    boost::promise<std::string> prms;
    boost::unique_future<std::string> fut = prms.get_future();

    boost::thread th(&thFun, std::move(prms)); // error C2248: 'boost::promise<R>::promise' : cannot access private member declared in class 'boost::promise<R>' 

    std::cout << "Hi from main!";
    std::string str = fut.get();
    std::cout << str << std::endl;
    th.join();

    return 0;
}

下面这行代码似乎引发了一个我不理解的问题:
boost::thread th(&thFun, std::move(prms));

编译器报错信息如下:

error C2248: 'boost::promise::promise' : cannot access private member declared in class 'boost::promise'

请问有谁能够提供解决方案吗?

先行感谢!


Boost.Threads 支持移动语义,因此要么您的编译器不支持它,要么您没有在 C++11 模式下进行编译(例如,在 GCC 中使用“-std=c++0x”)。 - R. Martinho Fernandes
我在其他示例中使用了std::move(),没有问题,所以我不认为是这个问题 - 但我可能错了。我还尝试过boost::move(),但结果是一样的。 - Pat Mustard
1个回答

7

boost::thread使用boost::bind处理具有附加参数的线程函数,这要求它们是可复制的。您可以通过指针或引用(例如使用boost::ref)传递promise,但这要求对象的生存期超过线程。在此示例中,这是可以的,但对于一个分离的线程,或者一个超出启动它的函数的生命周期的线程,这将防止在堆栈上使用boost::promise对象。


谢谢您的回复,安东尼。just::thread 的实现与这个有何不同? - Pat Mustard
just::thread 不依赖于 bind,因此它可以移动所有参数。 - Anthony Williams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接