【问题标题】:Should I use static or a namespace?我应该使用静态还是命名空间?
【发布时间】:2015-01-28 13:34:50
【问题描述】:

我有一个专用的硬件寄存器头文件,我创建了一个命名空间,就像这样,它包含我所有的硬件寄存器地址:

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,它使用头文件。

【问题讨论】:

  • C++11 我会使用强类型枚举

标签: c++ static namespaces


【解决方案1】:

两者本质上是等价的。

global-static 方法在 C++03 ([depr.static]) 中被弃用,取而代之的是未命名的命名空间,但后来 undeprecated by C++11 因为在一般情况下每个人都意识到 there is no objective benefit of one over the other

但是,为此,您可能会发现 enumenum class 更易于管理和惯用。

【讨论】:

    【解决方案2】:

    这两个是 100% 等价的,它们也是 100% 等价于同时省略 namespacestatic

    const uint32_t Register1                    = (0x00000000);
    const uint32_t Register2                    = (0x00000004);
    const uint32_t Register3                    = (0x00000008);
    const uint32_t Register4                    = (0x0000000c);
    

    原因很简单 - const 变量是 static,除非您明确声明它 extern

    但是,这看起来像使用枚举更可取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-24
      • 2012-06-17
      • 1970-01-01
      • 2011-11-09
      • 2012-09-22
      • 1970-01-01
      • 2012-01-04
      • 2015-11-25
      相关资源
      最近更新 更多