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);  
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...