C++ Thread 和 Promise:试图引用已删除的函数

C++ Thread and Promise : attempting to reference a deleted function

有点麻烦运行这个例子是网上找的

void asyncFun(std::promise<int> intPromise) {
    int result=5;
    try {
        // calculate the result
        intPromise.set_value(result);
    }
    catch (...) {
        intPromise.set_exception(std::current_exception());
    } 
}

int _tmain(int argc, _TCHAR* argv[]) {
    std::promise<int> intPromise;
    std::future<int> intFuture = intPromise.get_future();
    std::thread t(asyncFun, std::move(intPromise));
    std::cout << "Main thread" << std::endl;
    int result = intFuture.get(); // may throw MyException
    std::cout << result<<std::endl;
    return 0;
}

我得到了:

error C2280: 'std::promise::promise(const std::promise &)' : attempting to reference a deleted function c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional 1149 1 tryFuture

这是您使用的实现中的错误。可以考虑升级。

std::thread 的参数必须是 MoveConstructiblestd::promise 满足这些要求。

http://webcompiler.cloudapp.net处在线编译并运行(在main中添加了t.join())。作为一种变通方法,您可以将 "feeding" 视为一个引用(使用 std::ref 并从 promise 移出),但要注意使用这种变通方法的悬空引用。

这里的另一个解决方法是使用 std::shared_ptrstd::promise 作为函数的参数。

void asyncFun(std::shared_ptr<std::promise<int>> intPromise) {
    int result=5;
    try {
        // calculate the result
        intPromise->set_value(result);
    }
    catch (...) {
        intPromise->set_exception(std::current_exception());
    } 
}

int main() {
    std::promise<int> intPromise;
    std::future<int> intFuture = intPromise.get_future();
    auto sh = std::make_shared<std::promise<int>>(std::move(intPromise));
    std::thread t(asyncFun, sh);
    std::cout << "Main thread" << std::endl;
    int result = intFuture.get(); // may throw MyException
    std::cout << result<<std::endl;
    t.join();
    return 0;
}