微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c全局变量的后期实例化

我有代码,其中必须通过相当多的代码设置全局资源:
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);  
}

原文地址:https://www.jb51.cc/c/111297.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐