简体   繁体   中英

What does this sentence mean in paragraph §3.2/2 of the C++11 Standard?

The sentence is part of paragraph §3.2/2 :

A variable whose name appears as a potentially-evaluated expression is odr-used unless it is an object that satisfies the requirements for appearing in a constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) is immediately applied .

What exactly does the sentence in bold mean above?

Edit :

The answer to the question of which this one is considered a duplicate, doesn't say anything that could answer my question.

It means that when you use a constant as a constant, it's just like you were actually using a constant.

struct S {
  static const int i = 0;
};
int main() {
  return S::i;
}

Although S::i has an initialiser, it has no definition, but the text in your question makes a special exception for uses like this, where S::i is only accessed for its value. In that case, no definition is needed.

On the other hand, other uses do require a definition:

struct S {
  static const int i = 0;
};
int f(const int &i) {
  return i;
}
int main() {
  return f(S::i);
}

This program is invalid, and is accepted by some implementations, but rejected by others. The call to f requires an actual definition of S::i to exist, although if f gets inlined, it's possible for the lack of a definition to go undiagnosed.

On my system, if compiling and linking the second program without optimisations, I get:

$ g++ test2.cc -o test2
/tmp/ccdEsfxs.o:test2.cc:function main: error: undefined reference to 'S::i'
collect2: error: ld returned 1 exit status

To make it work, a definition needs to be provided, like so:

struct S {
  static const int i = 0;
};
const int S::i;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM