Consider the following code, provided by a colleague:
#include <array>
#include <string>
int main() {
const int size = 4;
return [size]() {
std::array<std::string, size> a; // *
return a.size();
}();
}
It's accepted by Clang 5.0.0 but rejected by GCC 7.2 with the error message for the starred line being:
error: '__closure' is not a constant expression
Which compiler is right?
The rule is actually intuitive: any occurrence of a variable that doesn't necessitate a capture refers to the original variable. [expr.prim.lambda]/11:
Every id-expression within the compound-statement of a lambda-expression that is an odr-use of an entity captured by copy is transformed into an access to the corresponding unnamed data member of the closure type. [ Note: An id-expression that is not an odr-use refers to the original entity, never to a member of the closure type. […] — end note ]
Clearly, the declared size
variable can be used in constant expressions, hence Clang is right.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments