Thursday, September 27, 2007

C++ static member variables

(This is an old post I posted in my old Live!Space Blog. Now just collect it here:-D )


老革命遇到新问题,呵呵。竟然今天(其实是一年多以前,呵呵)在这个topic上栽了一个小跟头。
See a class definition below:
class A
{
public:
static A* GetInstance();
ReleaseInstance();
private:
A();
virtual ~A();
static A* m_cInstance;
}
This is a typical definition of a singlton pattern. Is there any problem with this piece of code? When you compile it, you get nothing wrong. But when you actually access the class, you will get this:
error LNK2001: unresolved external symbol "private: static class A* A::m_cInstance" (?m_cInstance@A@xxxxxxx@xxx)
What's wrong here? Honestly, I haven't been using C++ for a while and actually I almost never use the singlton pattern in C++. I can say I'm expert in C or C#, but not really an expert in C++.
Well, to my suprise, lots of people got the same problem so the answer is found in minutes:
In C++, when you define a static member variable in a class, you are not actually define the variable, instead, you only give the symbolic definition of the class TYPE. What you need to do, is, you have to ACTUALLY DEFINE THE VARIABLE AGAIN OUTSIDE THE CLASS DEFINITION.
Well, so what you want to do to make it work is adding the following line at the beginning of A.cpp:
A* A::m_cInstance;
We know static variable in a class is actually not part of a class instance: it is a global variable, shared among all instance of that class type, and can also be access directly by the class type name. So, in C++ the language ask you to explictly define it as a global variable.
What a stupid design! I can't believe the C++ committee made such a stupid decision. There's absolutely no difficulty to let the compiler deal with the extra line with no attention from programmer. Why they don't do this?
Again, I have to say, C++ is really a gabage language. It is too old, it is out-dated. Modern languages like C# and Java are far better than C++ in every aspects, expect the performance. Well, in modern software industry, development productivity and program volunarity are far more important than running speed in most cases. When come to performance, why not comes a language that is as C# but compiled as native code and with no gabage collection? Is there a technical reason that C++ should survive(Yes, I know, keep the value of existing investments and .... job security:P)

No comments: