18

I was looking up ways to initialize static map in C++ and found this code:

struct A{ static map<int,int> create_map() { map<int,int> m; m[1] = 2; m[3] = 4; m[5] = 6; return m; } static const map<int,int> myMap; }; const map<int,int> A:: myMap = A::create_map(); 

However, if I change the last line to

const static map<int,int> A:: myMap = A::create_map(); 

Compiler complaints: 'static' may not be used when defining (as opposed to declaring) a static data member" ?

I wonder why? What's the logic or reasoning behind this ?

3 Answers 3

17
static int a = 0; // grandfathered and still useful, provides static *LINKAGE* // and static STORAGE DURATION static int X::a = 0; // confusing and illegal, is it static LINKAGE // or static STORAGE DURATION // or static MEMBERSHIP? 

static already had a meaning (in C) when used on a variable definition. It would be very surprising for C programmers learning C++ to find that meaning was changed sometimes, but not always.

So the new meaning (static membership) is only active inside the class definition (where C didn't allow the static keyword).

Sign up to request clarification or add additional context in comments.

Comments

4

Declaring a class member static means it is shared between all objects of this class.

When you add static to a variable definition outside of a class, it means this variable has file scope and is not visible outside this file.

If it would be allowed to

const static map<int,int> A:: myMap = A::create_map(); 

this would mean, you have a static member variable, which is not visible outside of this file. This just doesn't make sense.

3 Comments

or else it would mean static membership, which would be inconsistent.
@BenVoigt unlikely, static for membership there is redundant - you cannot define non-static members this way.
@Slava: Absolutely true, it'd be inconsistent and redundant, so two good reasons to forbid it. But I don't think the question was thinking of static linkage.
4

It's no different than

struct A { static int x; } int A::x; //legal static int A::x; //illegal 

Everything else is just more keywords thrown at this minimal, conceptually identical, example. A static member can only be declared static inside the class definition.

The

const map<int,int> A:: myMap = A::create_map(); 

outside the class is just a definition of the static member A::myMap. The extra static makes no sense there.

The reasoning behind this is probably to avoid confusion - a static free variable is kind of a "private" variable (to a translation unit). A member static is the opposite.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.