简体   繁体   中英

Nesting lambda expression with passing parameter by reference in c++

I am trying to use lambda expressions in C++. A example of lambda expression is demonstrated below. The input parameter of function f1 is a std::unique_ptr and the output parameter is also a std::unique_ptr.

    auto f1 = [](std::unique_ptr<float[]> &input_data, int size)->std::unique_ptr<float[]>
    {
        auto return_data = std::make_unique<float[]>(size);
        for (int loop_number = 0; loop_number < size; loop_number++)
        {
            return_data[loop_number] = input_data[loop_number] + 1;                  //  for example
        }
        return return_data;
    };

The non-nesting usage of function f1 is shown as below. It runs successfully.

    int size_for_testing = 100;
    auto test_object = std::make_unique<float[]>(size_for_testing);
    auto result = f1(test_object, size_for_testing);
    for (int loop_number = 0; loop_number < size_for_testing; loop_number++)
    {
        std::cout << result[loop_number] << std::endl;
    }

When it comes to the nesting case as shown as below, there is an error appeared.

auto result = f1(f1(test_object, size_for_testing), size_for_testing);

The compiler shows C2664 error with 'std::unique_ptr<float [],std::default_delete<float []>> main::<lambda_1>::operator ()(std::unique_ptr<float [],std::default_delete<float []>> &,int) const': cannot convert argument 1 from 'std::unique_ptr<float [],std::default_delete<float []>>' to 'std::unique_ptr<float [],std::default_delete<float []>> &' error message.

The result above should be as same as below.

    auto result1 = f1(test_object, size_for_testing);
    auto result = f1(result1, size_for_testing);

I am wondering that 1) Is it inappropriate to write lambda expression with passing parameters by reference? 2) Why the non-nesting usage of function f1 is fine but the error C2664 appears in the nesting usage?

OS: Windows 10 1909

IDE: Microsoft Visual Studio Community 2019 Version 16.4.5

The code attempts to bind an lvalue reference (1st arg of the outer f1 ) to a prvalue (return value of the inner f1 ), this is not allowed.

You could fix it by passing by const reference, std::unique_ptr<float[]> const &input_data .

I would consider having the parameter be float const * since the function's operation does not depend on how memory management worked for the input array. In fact std::span would be appropriate here too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM