我有一个专用的 HW 寄存器头文件,我创建了一个 namespace ,就像这样,它包含我所有的 HW 寄存器地址:
namespace{
const uint32_t Register1 = (0x00000000);
const uint32_t Register2 = (0x00000004);
const uint32_t Register3 = (0x00000008);
const uint32_t Register4 = (0x0000000c);
}
这是否比使用更好:
static const uint32_t Register1 = (0x00000000);
static const uint32_t Register2 = (0x00000004);
static const uint32_t Register3 = (0x00000008);
static const uint32_t Register4 = (0x0000000c);
我想命名空间的意义在于我们不会污染全局命名空间。是吗?
我有一个.cpp,它使用头文件。
最佳答案
两者本质上是等价的。
global-static
方法在 C++03 ([depr.static]
) 中被弃用,取而代之的是未命名的命名空间,但后来 undeprecated by C++11因为每个人都意识到there is no objective benefit of one over the other在一般情况下。
但是,为此,您可能会发现 enum
或 enum class
更易于管理和惯用。
关于c++ - 我应该使用静态还是命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28193604/