[英]Which linkages are granted to non-local member variables in c++?
I assume that a class's data members have linkage(or no linkage) like below我假设一个类的数据成员有链接(或没有链接),如下所示
Is that correct?那是对的吗?
class AAA {
public: // this doesn't matter
int var1; // no linkage
const int var2 = 0; // no linkage
static int var3; // external linkage (declaration)
static const int var4 = 0; // external linkage (declaration + definition)
};
int AAA::var3 = 0; // external linkage (definition)
First of all I questioned about which linkages are granted to data members首先我质疑哪些链接被授予数据成员
and my assumption was right and MM answered it's OK too我的假设是对的,MM也回答说没关系
I double checked in the standard and yes, linkages are correct like I and MM said above我仔细检查了标准,是的,链接是正确的,就像我和 MM 上面说的那样
But as MM mentioned I misunderstood which one is declaration or definition但正如 MM 提到的,我误解了哪个是声明或定义
It's a bit out of topic but I answer it by myself for someone who read this in future这有点题外话,但我自己回答了将来阅读此内容的人
[1] if it comes to non-static data member [1] 如果是非静态数据成员
struct A {
int var1; // definition (initial value is 0)
int var2 = 100; // definition (initial value is 100)
};
[2] if it comes to static const [2] 如果是静态常量
struct A {
static const int var1 = 100; // declaration (initial value is 100)
static const int var2; // declaration (initial value is 0)
};
const int A::var1; // definition (an option for odr-used situation)
const int A::var2 = 10; // definition
[3] if it comes to static constexpr [3] 如果是静态 constexpr
constexpr
data members are interesting and work differently constexpr
数据成员很有趣并且工作方式不同
because from C++17 a data member with constexpr
implies inline
因为从 C++17 开始,带有
constexpr
的数据成员意味着inline
and inline
actually define it并
inline
实际定义它
plus every inline
data members in every translation units are guaranteed to have same only one definition加上每个翻译单元中的每个
inline
数据成员都保证只有一个相同的定义
( https://eel.is/c++draft/depr.static.constexpr ) ( https://eel.is/c++draft/depr.static.constexpr )
struct A {
static constexpr int n = 5; // definition (declaration in C++ 2014)
};
constexpr int A::n; // redundant declaration (definition in C++ 2014)
for example if I have 2 translation units like below例如,如果我有 2 个如下的翻译单元
// foo.cpp
#include <iostream>
class AAA {
public:
static constexpr int var = 10;
};
void foo() {
std::cout << &AAA::var << std::endl;
}
// main.cpp
#include <iostream>
class AAA {
public:
static constexpr int var = 10;
};
void foo();
int main() {
std::cout << &AAA::var << std::endl;
foo();
}
and result is like below结果如下
$ g++ -std=c++17 main.cpp foo.cpp
$ ./a.out
0x564ba82a3a54
0x564ba82a3a54
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.