开发者

Isn't a const variable at namespace scope implicitly static?

I know that static const int x = 42; at namespace scope is equivalent to const int x = 42; because const variables are implicitly static (they must be declared extern to be given external linkage). Every translation unit that includes this declaration gets a local copy of x.

Does this only apply to certain (perhaps integer?) types? I have the following code in a header file:

namespace XXX {
    static const char* A = "A";
    static const char* B = "B";
    static const char* C = "C"; // and so on
}

(PLEASE sp开发者_如何学运维are me the comments on why I should not be using C-style strings -- this is legacy code)

This header is included from several source files, and all is fine (each compilation unit gets its own copy of these char*'s). I would have thought that I could remove the static from these, as it is redundant, but when I do, I get link errors about the symbols being already defined in another object. What am I missing here? Are these const char*'s not implicitly static?


In your example, you are creating a pointer to a constant (block of) char rather than creating a constant pointer to a char. Thus, your pointer isn't constant and so isn't implicitly static.

You need to declare x as const char *const A, which creates a constant pointer to a constant (block of) char.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜