1

I can see so many language who can define a function when passing it as argument. However there is something i cannot understand in C++, here is the snippet.

::android::hardware::camera::common::V1_0::Status err = ::android::hardware::camera::common::V1_0::Status::OK;
std::vector<std::string> devices;
hardware::Return<void> ret =
    hidlSecureCamera->getCameraIdList([&err, &devices](
        ::android::hardware::camera::common::V1_0::Status idStatus,
        const hidl_vec<hidl_string>& cameraDeviceIDs) {
    err = idStatus;
    if (err == Status::OK) {
        for (size_t i = 0; i < cameraDeviceIDs.size(); i++) {
            devices.push_back(cameraDeviceIDs[i]);
        }
    } });

As you can see, the prototype of getCameraIdList is Return<void> SecureCamera::getCameraIdList(getCameraIdList_cb _hidl_cb). So it only accept one function as argument.

However, i cannot understand the meaning of [&err, &devices]. They're already variables defined before. So i should be able to use it directly, why i need [&err, &devices]?

demonguy
  • 1,471
  • 4
  • 16
  • 27
  • https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11 – M.M May 25 '19 at 06:18
  • Are you asking what the syntax `[&err, &devices]` means, or are you asking what factors informed that design aspect of lambdas in C++? – Sneftel May 25 '19 at 06:18

1 Answers1

3

However, i cannot understand the meaning of [&err, &devices]

What you have there is a lambda function.

Use of [&err, &devices] indicates that err and devices are captured by reference by the lambda function.

That can be made more readable by using:

auto func = [&err, &devices](::android::hardware::camera::common::V1_0::Status idStatus,
                             const hidl_vec<hidl_string>& cameraDeviceIDs)
{
   err = idStatus;
   if (err == Status::OK) {
      for (size_t i = 0; i < cameraDeviceIDs.size(); i++) {
         devices.push_back(cameraDeviceIDs[i]);
      }
   }
};

hardware::Return<void> ret = hidlSecureCamera->getCameraIdList(func);

Further reading: https://en.cppreference.com/w/cpp/language/lambda

R Sahu
  • 196,807
  • 13
  • 136
  • 247