在C ++ 17或更高版本中的哪里初始化静态const成员? [英] Where to initialize static const member in c++17 or newer?
问题描述
问题是在C ++ 17或更高版本中在哪里初始化静态const成员?请考虑以下两种在c ++中初始化静态const成员的解决方案:
The questions is where to initialize static const member in c++17 or newer? Please consider the following two solutions for initializing a static const member in c++:
解决方案1(适用于c ++ 14或更早版本):
//foo.h:
#include <iostream>
struct foo{
static const std::string ToBeInitialized;
};
//foo.cpp
#include <iostream>
#include "foo.h"
const std::string foo::ToBeInitialized{"with a value"};
解决方案2(适用于c ++ 17或更高版本):
//foo.h:
#include <iostream>
struct foo{
inline static const std::string ToBeInitialized{"with a value"};
};
当前,我更喜欢解决方案2,因为它更短.使用解决方案1或解决方案2的优点和缺点是什么?
Currently I prefer solution 2 because it is shorter. What are the advantages and disadvanteges of using solution 1 or solution 2?
我很清楚以下事实:有关静态const初始化的几个问题:
I am well aware of the fact that there are several questions dealing about static const initialization:
但是,以上所有问题均未明确处理c ++ 17或更高版本.
However non of the above questions deal with c++17 or newer explicitly.
推荐答案
据我了解,区别在于非内联"静态变量被编译为单个实例,而内联"变量被编译为单个实例.每个翻译单元将其编译为一个,然后由链接器消除为一个.这表示内联"消除只能在链接的代码内发生,它不能跨动态链接的代码.我相信此线程中已经提供了很好的解释内联静态const与静态const变量.祝你好运!
As I understand it the difference is that the "non-inline" static variable gets compiled to a single instance while the "inline" one gets compiled to one per translation unit and then eliminated to a single one by the linker. This means the "inline" elimination can occur only within the linked code, it can NOT cross dynamically linked code. I believe a good explanation has been provided in this thread Inline static const vs static const variable . Good luck!
这篇关于在C ++ 17或更高版本中的哪里初始化静态const成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!