开发者

Why can't initialize the static member in a class in the body or in the header file?

开发者 https://www.devze.com 2022-12-24 10:36 出处:网络
Could any body offer me any reason about that? If we do it like that, what\'s the outcome? Compil开发者_C百科e error?The problem is that static initialization isnt just initialization, it is also def

Could any body offer me any reason about that?

If we do it like that, what's the outcome? Compil开发者_C百科e error?


The problem is that static initialization isnt just initialization, it is also definition. Take for example:

hacks.h :

class Foo
{
public:
    static std::string bar_;
};

std::string Foo::bar_ = "Hello";

std::string GimmeFoo();

main.cpp :

#include <string>
#include <sstream>
#include <iostream>

#include "hacks.h"

using std::string;
using std::ostringstream;
using std::cout;

int main()
{

    string s = GimmeFoo();
    return 0;
}

foo.cpp :

#include <string>
#include <sstream>
#include <iostream>

#include "hacks.h"

using std::string;
using std::ostringstream;
using std::cout;

string GimmeFoo()
{
    Foo foo;
    foo;
    string s = foo.bar_;

    return s;
}

In this case, you can't initialize Foo::bar_ in the header because it will be allocated in every file that #includes hacks.h. So there will be 2 instances of Foo.bar_ in memory - one in main.cpp, and one in foo.cpp.

The solution is to allocate & initialize in just one place:

foo.cpp :

...
std::string Foo::bar_ = "Hello";
...


It is just a limitation in the language it self. Hopefully, when C++0x becomes reality, this limitation would go away.

I think this page gives a somehow good reason:

One of the trickiest ramifications of using a static data member in a class is that it must be initialized, just once, outside the class definition, in the source file. This is due to the fact a header file is typically seen multiple times by the compiler. If the compiler encountered the initialization of a variable multiple times it would be very difficult to ensure that variables were properly initialized. Hence, exactly one initialization of a static is allowed in the entire program.

0

精彩评论

暂无评论...
验证码 换一张
取 消