c++ - 使用 static、const、constexpr 的全局声明/初始化

标签 c++ c++11

在 C++ 或 C++11 中,对于以下声明//初始化,

// global scope
const int a = 1; // line 1
static const int b = 2; // line 2
constexpr int c = 3;  // line 3
static constexpr int d = 4; // line 4
constexpr int e = a + b + c*d; // line 5
static constexpr int f = a - b - c*d; // line 6

This question表示在文件范围内,C++ 中的第 1 行和第 2 行没有区别。 3 号线和 4 号线呢?

第4行和第5行有区别吗?

第5行和第6行有区别吗?

最佳答案

不,不应该有任何区别(当然除了它们的值)因为 constexpr 和 const 暗示内部链接:

[C++11: 3.5/3]: A name having namespace scope (3.3.6) has internal linkage if it is the name of

  • a variable, function or function template that is explicitly declared static; or,
  • a variable that is explicitly declared const or constexpr and neither explicitly declared extern nor previously declared to have external linkage; or
  • a data member of an anonymous union.

关于c++ - 使用 static、const、constexpr 的全局声明/初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31129919/

相关文章:

c++ - 使用 RAII 从 C 风格的 API 管理资源

c++ - 遇到段错误 : It looks like my comparator is trying to compare nodes out of scope

c++ - 如何将智能指针返回到成员变量?

c++ - 在不创建 Functor 类的情况下使用 Functors 时出错?

c++ - wglCreateContextAttribsARB 未定义?

C++0x : conditional operator, x值和decltype

c++ - 在多线程 VS 代码中出现调试错误并且无法找到问题

c++ - 获取域 Controller 名称

c++ - MatrixXf::Random 总是返回相同的矩阵

c++ - 错误在 `./2' : free(): invalid pointer: 0x000000000096044c *** Aborted (core dumped)