【问题标题】:Difference of static const and static when returning a static variable返回静态变量时static const和static的区别
【发布时间】:2013-03-18 13:46:39
【问题描述】:

最好用代码解释:

static Unit& None() { static Unit none(....); return none;}

有什么区别?

static const Unit& None() { static Unit none(....); return none;}

【问题讨论】:

  • 你问Unit&const Unit&有什么区别?
  • 正如@DrewDormann 所说,constUnit& 一起使用,而不与static 一起使用。

标签: c++ static constants static-methods


【解决方案1】:

函数前面的static与函数内部的static完全不同1。特别是,它与返回类型完全无关。这些函数的返回类型和这里一样:

Unit& None() { static Unit none(....); return none;}

const Unit& None() { static Unit none(....); return none;}

即没有static 限定符。

因此区别仅在Unit&Unit const&之间:第一个允许修改返回值,第二个不允许。


1) 对于类成员,static表示该函数不能访问该类的实例变量和实例函数;在命名空间范围的函数上,static 表示函数符号不是从编译单元导出的。

【讨论】:

    【解决方案2】:

    您正在返回对静态对象/变量的引用。因此可以为函数赋值,然后更改该对象/变量的值。

    第二个拒绝改变none的值:

    static int& func1()
    {
        static int a = 1; return a;
    }
    
    static const int& func2()
    {
        static int a = 1; return a;
    }
    
    int main()
    {
        func1() = 10;    // OK
        func2() = 10;    // error: assignment of read-only location
    }
    

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 2011-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多