在[& capture]和[& local = capture]在lambdas中捕获之间有什么区别?

时间:2017-09-21 15:38:14

标签: c++ lambda c++14

if(!setFlag)
{
    Intent myIntent = new Intent(FirstActivity.this, LogoutService.class);
    pendingIntent = PendingIntent.getService(FirstActivity.this, 0, myIntent, 0);
    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.MINUTE, 10); //Minutes
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}

我是否理解正确,只有a和b之间的区别是别名的创建" v"为" vec"在b情况下还是有更多的东西?

2 个答案:

答案 0 :(得分:11)

在这种情况下,没有真正的区别。但是,如果您按值捕获,则会有所不同:

const std::vector<int> vec; // note const

auto foo = [vec]() mutable {
   // can't change vec here since it is captured with cv-qualifiers
};

auto bar = [v = vec]() mutable {
    // can change v here since it is captured by auto deduction rules
    // (cv-qualifiers dropped)
};

答案 1 :(得分:5)

基本上没有。它只是允许您为捕获的值提供自定义名称。

但是请注意,当您想要将对象实际移动到闭包中时,需要使用此语法(称为init捕获):

std::vector<int> vector;
auto lambda = [vec = std::move(vector)]() { /* the lambda owns the vector now */ });