相关疑难解决方法(0)

std :: async使用绑定到lambda的rvalue引用

我正在尝试将一个rvalue引用绑定到一个lambda使用std::bind,但是当我把它扔进一个std::async调用时我遇到了问题:( 来源)

auto lambda = [] (std::string&& message) {
    std::cout << message << std::endl;
};
auto bound = std::bind(lambda, std::string{"hello world"});
auto future = std::async(bound); // Compiler error here
future.get()
Run Code Online (Sandbox Code Playgroud)

这会发出编译器错误我不确定如何解释:

错误:'class std :: result_of(std :: basic_string)>&()>'中没有​​名为'type'的类型

这里发生了什么?有趣的是,稍微修改确实可以按预期编译和工作.如果我改为std::string{"hello world"}c字符串文字,一切正常:( 来源)

auto lambda = [] (std::string&& message) {
    std::cout << message << std::endl;
};
auto bound = std::bind(lambda, "hello world");
auto future = std::async(bound);
future.get(); // Prints "hello world" as expected
Run Code Online (Sandbox Code Playgroud)

为什么这有效但不是第一个例子?

c++ lambda stdbind c++11

8
推荐指数
1
解决办法
502
查看次数

std :: async和对象副本

我正在尝试std::async并最终得到一个看起来像这样的代码:

class obj {
public:
    int val;

    obj(int a) : val(a) {
        cout << "new obj" << endl;
    }
    ~obj() {
        cout << "delete obj" << endl;
    }
};


void foo(obj a) {

    this_thread::sleep_for(chrono::milliseconds(500));
    cout << a.val << endl;
}

int main(int argc, int **args) {

    obj a(5);
    auto future = async(foo, a);
    future.wait();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果是:

new obj
delete obj
delete obj
delete obj
5
delete obj
delete obj
delete obj
Run Code Online (Sandbox Code Playgroud)

然后我试图改变void foo(obj a)的 …

c++ c++11

5
推荐指数
1
解决办法
725
查看次数

标签 统计

c++ ×2

c++11 ×2

lambda ×1

stdbind ×1