捕获lambda表达式中的指针? [英] Capturing pointers in lambda expression?

查看:496
本文介绍了捕获lambda表达式中的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用lambda表达式的函数。

I have a function that uses a lambda expression.

std::vector<Bar*> mBars;

void foo(Bar* bar)
{
    auto duplicateBars = std::remove_if(mBars.begin(), mBars.end(),
        [bar] (const Bar* const &element)
        {
            return bar == element;
        });

    mBars.erase(duplicateBars, mBars.end());
}

后来,我检查了代码,意识到我可以在foo的签名中添加两个const。

Later, I reviewed the code and realized I could add two consts to foo's signature.

void foo(const Bar* const bar);

bar 的指针和数据现在常量,但是出于lambda表达式的目的,指针本身是常量,因为我是按值捕获的。但是,指向的数据可以更改,无法更改,因为在lambda捕获中不允许 const

bar's pointer and data is now constant, but for the purpose of the lambda expression the pointer itself is constant, because I captured by value. However, the data pointed to can be changed and there is no way to change this, because const is not allowed in the lambda capture.

这对我来说并不直观。我的解释正确吗?我可以使用第二个签名,但是不能保护数据不会在lambda表达式中更改。

This is unintuitive to me. Is my interpretation correct? I can use the second signature, but I cannot protect the data from being changed in the lambda expression.

推荐答案


但是,指向的数据可以更改,并且无法更改,因为在lambda捕获中不允许使用const。

However, the data pointed to can be changed and there is no way to change this, because const is not allowed in the lambda capture.

否,当在lambda表达式中按值捕获时,将保留constness,即捕获指向 const 数据的指针将防止对lambda内部的数据进行更改。

No, when capturing by value in a lambda expression constness is preserved, i.e. capturing a pointer to const data will prevent changes to the data inside the lambda.

int i = 1;
const int* ptr = &i;

auto func = [ptr] {
    ++*ptr; // ERROR, ptr is pointer to const data.
}

lambda还会添加顶级常量指向按值捕获时的指针(除非使用 mutable )。

A lambda will also add top-level constness to pointers when capturing by value (unless using mutable).

auto func = [ptr] {
    ptr = nullptr; // ERROR, ptr is const pointer (const int* const).
}

auto func = [ptr] () mutable { // Mutable, will not add top-level const.
    ptr = nullptr; // OK
}




我可以使用第二个签名,但是我不能保护数据不会在lambda表达式中被更改。

I can use the second signature, but I cannot protect the data from being changed in the lambda expression.

您可以通过以下方式保护数据在lambda中不被更改:使用 const

You can protect the data from being changed inside the lambda by using const.

const Bar* bar = &bar_data;
auto b = [bar] (const Bar* element) { // Data pointed to by bar is read-only.
    return bar == element;
};

同样,lambda表达式采用类型为 const Bar * const&的参数。 ,即引用指向const数据的const指针。无需引用,只需引用 const Bar *

Also the lambda expression takes a parameter of type const Bar* const &, i.e. reference to const pointer to const data. No need to take a reference, simply take a const Bar*.

有关指针和<$ c的更多信息$ c> const : const int *,const int * const和int const *有什么区别?

这篇关于捕获lambda表达式中的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆