Do c++ guarantee header-initialized static const member to share a single instance across compile units and libraries?

萝らか妹 提交于 2020-06-16 09:51:02

问题


Let's consider a code

header:

class uid
{
public:
    uid () {++i; }
    static int i;
};

class foo
{
public:
    const static uid id;
}   

source:

static int uid::i = 0;

The header could be included into several source files, shared between compiler units and libraries.

Is it guaranteed that there would be only one instance off foo::id, that foo::id::id() would be called once at run-time and, the most important thing, would foo::id.i be the same everywhere in the program and it's libraries? On the other hand another shared header could have bar class with it's own static const uid id which is expected to differ from foo's one. Is it also guaranteed? If so, where actually foo::id symbol is stored, especially in case of shared (dynamic-linked) libraries.

On some reason c++ disables

class foo
{
public:
    const static int id = create_uid(); // forbidden
}   

allowing only compile-time const initialisation or initialization in source file. So there was some reason to disable this kind of approach.


回答1:


Yes, that is guaranteed.

The symbol lives in the translation unit built from the source file where the object was defined. Indeed, that's why we have to define it in one!

The linker makes sure all the references from the copies of that header across your project all match up to the sole definition.

As for why C++ doesn't let you initialise static members inline: it does, but not in C++98. You need C++17 for that.



来源:https://stackoverflow.com/questions/61781901/do-c-guarantee-header-initialized-static-const-member-to-share-a-single-instan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!