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
352 views
in Technique[技术] by (71.8m points)

c++11 - What is the correct way to initialize static data members in C++ (98, 11 and 14)

What is the right way to initialize static data members in C++? I'm also interested in how it has changed from C++98, to C++11 to C++14.

Here is an example:

// bufferedOutput.h
class BufferedOutput
{
 // Static member declaration.
 static long bytecount;
};

// bufferedOutput.cpp
long BufferedOutput::bytecount = 50;

Are there other ways to initialize static data members?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The rules have always been as follows:

  • A const static data member (SDM) of integral or enumeration type can be initialised in class with a constant expression.

  • A constexpr SDM must be initialised in class with a constant expression.

    C++17 no longer requires an initializer when the default constructor initialises every member. Also, constexpr SDMs are implicitly inline variables, which makes their declaration a definition (external definitions are now deprecated).

  • Other kinds of SDMs can have an initializer at their definition (which is in class if that SDM is declared inline).

Nothing has substantially changed between C++03 and C++11+ for code that is valid in both languages.

Note that for SDMs that are not inline, the in-class declaration is not a definition—regardless of whether an initializer is provided—and they must be defined if they are odr-used.

As of C++17, we can make your SDM inline, which makes its in-class declaration a definition:

class BufferedOutput
{
  static inline long bytecount = 50;
};

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

...