What exactly is the meaning of the footnote mentioned in [expr.ref] / 1?

[expr.ref] / 1 :

A postfix expression followed by a dot .or arrow ->, optionally followed by the keyword template(17.2), and then followed by an id expression, is a postfix expression. A postfix expression before a point or arrow is evaluated: 67 the result of this evaluation, together with the id-expression, determines the result of the entire postfix expression.

67) If an access expression to a member of a class is evaluated, a subexpression is evaluated even if the result is not needed to determine the value of the entire postfix expression, for example, if the id expression denotes a static member.

+6
source share
1 answer

If a member is defined as static, then for the class there is only one copy of this member, and not one copy for each instance of the class. Static members can be referenced through an instance (object) of a class. The footnote explains that the expression that identifies the instance is evaluated (and any side effects do occur), even if you don't need to know which instance of the object you get in order to know the value of the static member.

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 is only one object s, and its value 42, but the expression arr[index()]is still evaluated, although its result is not required to determine the value s.

Output:

index returns 5
42
+6
source

All Articles