Defining a static data member in the class definition

suggest change

A static data member of the class may be fully defined within the class definition if it is declared inline. For example, the following class may be defined in a header. Prior to C++17, it would have been necessary to provide a .cpp file to contain the definition of Foo::num_instances so that it would be defined only once, but in C++17 the multiple definitions of the inline variable Foo::num_instances all refer to the same int object.

// warning: not thread-safe...
class Foo {
  public:
    Foo() { ++num_instances; }
    ~Foo() { --num_instances; }
    inline static int num_instances = 0;
};

As a special case, a constexpr static data member is implicitly inline.

class MyString {
  public:
    MyString() { /* ... */ }
    // ...
    static constexpr int max_size = INT_MAX / 2;
};
// in C++14, this definition was required in a single translation unit:
// constexpr int MyString::max_size;

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Inline variables:
* Defining a static data member in the class definition

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
126 Inline variables
134 Semaphore
136 Debugging
139 Mutexes
142 decltype