且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

捕获lambda表达式中的指针?

更新时间:2022-03-09 06:16:06


但是,指向的数据可以更改,并且无法更改,因为在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*.

有关指针和 const : const int *,const int * const和int const *有什么区别?