-5

why can't push static const member into vector?

static const, static const constexpr, can't push into static, non-static, and static const outside class, can push sorry. I missed scope specifier , well I mean the situation that added specifier, can’t push static const member

struct A {
    static const constexpr int sccv = 0;
    static const int scv = 0;
    static int sv = 0;
    const int cv = 0;
};

int main () {
    std::vector<int> vec;
    vec.push_back(A::sccv);            // error
    vec.push_back(A::scv);             // error
    vec.push_back(A::sv);              // pass
    vec.push_back((new A())->cv);   // pass
    static const int sc = 0;
    vec.push_back(sc);              // pass
}
mewo1234
  • 311
  • 3
  • 10

1 Answers1

2

First I will assume that you wrote A:: at point-of-use, otherwise none of this code would have compiled.

When you "use" an object that has namespace-scope or is a class member, that is declared static, you must generally have a definition for it somewhere.

It might seem weird that a definition is needed even though you provided an initialiser at the point of declaration. That's because providing an initial value is only a small part of what a definition does. The more important part is giving the object a home, somewhere to live, specifying which compiled "module" will host the memory required for the object's existence. Like any object, your static member needs to be instantiated somewhere; the fact that it is lexically declared inside a class definition is a bit of a red herring.

So:

struct A {
    static const constexpr int sccv = 0;
    static const int scv = 0;
    static int sv = 0;
    const int cv = 0;
};

// In precisely one source file:
const constexpr int A::sccv;
const int A::scv;
int A::sv;

Now you won't get that "undefined reference" linker error any more.

There are some exceptions to the rule, and there are some scenarios in which compiler optimisations result in your program appearing to work regardless.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • Thanks, it’s weird that definition is still needed if already given initial value in declaration – mewo1234 Feb 13 '18 at 01:34
  • @mewo1234: It's because providing an initial value is only a small part of what a definition does. The more important part is giving the object a home, somewhere to live, specifying which compiled "module" will host the memory required for the object's existence. Like any object, your `static` member needs to be instantiated somewhere; the fact that it is lexically declared inside a class definition is a bit of a red herring. – Lightness Races in Orbit Feb 13 '18 at 01:35