简体   繁体   中英

Constructor initializer list and static member (private vs protected)

It is clear that a data member of a class declared as static is incorrect to be initialized in ctor initializer list (because it "is not a member" of an object). But it works fine if it is a protected member. Why?

// foo.h
class Foo {
public:
  explicit Foo();
  ~Foo() = default;
protected:
  static int kProtected;
private:
  static int kPrivate;
}
// foo.cpp
Foo::Foo() 
    : kProtected(1), // OK (?!)
      kPrivate(1) {} // error C2438: 'kPrivate': cannot initialize static class data via constructor

From §10.3.8.2 Classes/Static members/Static data members of the draft C++20 standard:

Static data members are initialized and destroyed exactly like non-local variables.

so your compiler is incorrect.

Which version of visual studio are you using? Older visual studios were notorious for treating standard more as a guide. On clang your code gets:

<source>:12:7: error: member initializer 'kProtected' does not name a non-static data member or base class

    : kProtected(1), // OK (?!)

      ^~~~~~~~~~~~~

<source>:13:7: error: member initializer 'kPrivate' does not name a non-static data member or base class

      kPrivate(1) {} // error

      ^~~~~~~~~~~

2 errors generated.

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