Strange bracket-parentheses notation in C++, looking somewhat like a for each loop

后端 未结 3 1500
醉梦人生
醉梦人生 2021-01-22 08:33

So this is how the code looks:

auto generateHash = [](std::vector &files) -> std::shared_ptr {
    // Other code here
}
         


        
3条回答
  •  太阳男子
    2021-01-22 09:17

    What does this mean?

    It's a lambda - a function object. You can call it like a function with a a vector of files (passed by mutable reference, for some weird reason), and it a returns string (managed by a shared pointer, for some weird reason).

    std::vector files = get_some_files();
    std::shared_ptr hash = generateHash(files); // call the lambda
    

    Is it a for each loop?

    No. That looks like

    for (auto thing : sequence) {/* code */}
    

    What do the brackets in the beginning do?

    They signify that it's a lambda. They can contain the capture list of local variables that you want to make available to the code inside the lambda.

    What does the arrow mean?

    That's a trailing return type. In C++11, you can use that syntax with normal functions if you want; but it's the only way to specify a lambda's return type.

    I can't find it in the C++ reference.

    It's right here: http://en.cppreference.com/w/cpp/language/lambda

提交回复
热议问题