Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

c++ - Defining constexpr static data members

So, I'm aware that in C++ static members can be initialized inside the class if they are a const literal type like the following

class test{
public:
        static constexpr int stc = 1;
private:
        int a = 0;
        int b = 0;
        int c = 0;
};

and the static constexpr variable stc can be used where the compiler can directly substitute the value of the member i.e

int main () {int array[test::stc];}  

However, if used in a context where the value cannot be directly substituted by the compiler:

int main() { const int &cs = test::stc; } 

then the compiler (clang) generates an error

c++ -std=c++11 -pedantic    t.cpp   -o t
Undefined symbols for architecture x86_64:
  "test::stc", referenced from:
      _main in t-a8ee2a.o
ld: symbol(s) not found for architecture x86_64

unless the static member is defined outside the class like so:

constexpr int test::stc;

Why is this the case?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In

int main() { const int &cs = test::stc; } 

test::stc is odr-used while in

int main () {int array[test::stc];}  

it is not.

The following example from the C++11 Standard supports the above idea.

struct S { static const int x = 0; };
const int &f(const int &r);  
int n = b ? (1, S::x)    // S?::?x is not odr-used here
          : f(S::x);     // S?::?x is odr-used here, so a definition is required

Looking at it from practical point of view, cs will be an invalid reference unless test::stc has an address. array, on the other hand, needs just the value of test::stc, which can be evaluated at compile time. array does not need the address of test::stc to be a valid object.

An object that is odr-used must be defined exactly once in a program.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...