c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例? [英] Do c++ guarantee header-initialized static const member to share a single instance across compile units and libraries?

查看:51
本文介绍了c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑一个代码

标题:

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

class foo
{
public:
    const static uid id;
}   

来源:

static int uid::i = 0;

头文件可以包含在多个源文件中,在编译器单元和库之间共享.

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

是否保证 foo::id 只有一个实例,foo::id::id() 将在运行时调用一次-时间,最重要的是,foo::id.i 在程序及其库的任何地方都相同吗?另一方面,另一个共享头可能有 bar 类,它自己的 static const uid id 预计与 foo 的不同.也有保障吗?如果是这样,实际存储 foo::id 符号的位置,尤其是在共享(动态链接)库的情况下.

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.

由于某种原因 C++ 禁用

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.

推荐答案

是的,这是有保证的.

符号位于从定义对象的源文件构建的翻译单元中.确实,这就是为什么我们必须将其定义为一个!

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.

至于为什么 C++ 不允许您内联初始化静态成员:它允许,但在 C++98 中不允许.为此,您需要 C++17.

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.

这篇关于c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆