问题
[expr.ref]/1:
A postfix expression followed by a dot .
or an arrow ->
, optionally followed by the keyword template
(17.2),
and then followed by an id-expression, is a postfix expression. The postfix expression before the dot or arrow
is evaluated;67 the result of that evaluation, together with the id-expression, determines the result of the
entire postfix expression.
67) If the class member access expression is evaluated, the subexpression evaluation happens even if the result is unnecessary to determine the value of the entire postfix expression, for example if the id-expression denotes a static member.
回答1:
If a member is defined as static
, then there is only one copy of that member for the class, not one copy for each instance of the class. Static members can be referenced via an instance (an object) of the class. The footnote clarifies that the expression identifying the instance is evaluated (and any side effects take place) even though you don't need to know which instance object you're accessing to know the value of the static member.
An example:
#include <iostream>
class foo {
public:
static int s;
};
int foo::s = 42;
int index() {
std::cout << "index returns 5\n";
return 5;
}
int main() {
foo arr[10];
std::cout << arr[index()].s << "\n";
}
There's only one s
object, and its value is 42
, but the expression arr[index()]
is still evaluated, even though its result isn't needed to determine the value of s
.
The output is:
index returns 5
42
来源:https://stackoverflow.com/questions/44529581/what-exactly-is-the-meaning-of-the-footnote-mentioned-in-expr-ref-1