Here's another title of my question: Is private/protected member access in a lambda expression allowed?
Facts I know:
-
Class members declared as private can be used only by member functions and friends (classes or functions) of the class. --- Microsoft Doc
-
A lambda can access, or capture, variables from the surrounding scope. --- Microsoft Doc
- A lambda that captures nothing can convert to a function pointer.
In short, below is a code snippet that demonstrates my confusion.
I've tested it on GCC 7.4.0(Ubuntu 18.04 on WSL) and CL 19.22.27905(VS2019 Community), and on both platform this code has been passed.
class A {
int a = 0;
public:
void access();
};
A* getPointer() {
static A a;
return &a;
}
void runFunction(void(*fp)(int i)) {
fp(1);
}
void A::access() {
runFunction([](int i){
getPointer()->a = i; // Here, is the access of variable `a` legal?
});
}
// Just for running the program
int main() {
getPointer()->access();
}
On one hand, this is legal because this variable is used by member functions(access()) the class(Fact 2).
But on the other hand, it isn't directly accessed by that function. Rather, it is accessed in the lambda expression, which is converted to a function pointer.
In this case, the A::access() should be similar as this:
void lambda(int i) {
getPointer()->a = i;
}
void A::access() {
runFunction(lambda);
}
This code certainly has syntax error.
And I'm a bit confused, mostly about the word surrounding of Fact 2.
Aucun commentaire:
Enregistrer un commentaire