加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c全局变量的后期实例化

发布时间:2020-12-16 03:28:02 所属栏目:百科 来源:网络整理
导读:我有代码,其中必须通过相当多的代码设置全局资源: globalClass foo; // global variable / object; give it a memory space to livevoid doSomething( void ){ foo.bar(); // use the global foo object}int main( int argc,const char *argv[] ){ foo( arg
我有代码,其中必须通过相当多的代码设置全局资源:
globalClass foo;  // global variable / object; give it a memory space to live

void doSomething( void )
{
  foo.bar();      // use the global foo object
}

int main( int argc,const char *argv[] )
{
  foo( argc );   // foo can only be instantiated in main as it's using
                 // information that's only available here

  doSomething(); // use the global foo object

  return 0;
}

正如你所看到的,foo具有全局范围 – 但是为了调用它的构造函数,我需要一些仅在main中可用的信息.

我怎样才能做到这一点?

我能想出的唯一解决方案是使foo成为指向globalClass的指针 – 但是每次我使用foo时都会导致指针解除引用.在紧密循环中使用时,这可能会产生性能问题……

PS:在真正的程序main和doSomething将存在于不同的文件中.并且当然保证foo在实例化之前不会被访问.

解决方法

如何将foo作为函数内的静态变量?这样,它只在调用函数时被实例化:
globalClass& getThing()
{
  static globalClass thing;
  return thing;
}

void doSomething(const globalClass& thing);

int main()
{
  const globalClass& x = getThing();
  doSomething(x);  
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读